[project @ 2001-08-24 09:02:39 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreTidy.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Tidying up Core}
5
6 \begin{code}
7 module CoreTidy (
8         tidyCorePgm, tidyExpr, tidyCoreExpr,
9         tidyBndr, tidyBndrs
10     ) where
11
12 #include "HsVersions.h"
13
14 import CmdLineOpts      ( DynFlags, DynFlag(..), opt_OmitInterfacePragmas )
15 import CoreSyn
16 import CoreUnfold       ( noUnfolding, mkTopUnfolding, okToUnfoldInHiFile )
17 import CoreFVs          ( ruleSomeFreeVars, exprSomeFreeVars )
18 import CoreLint         ( showPass, endPass )
19 import VarEnv
20 import VarSet
21 import Var              ( Id, Var )
22 import Id               ( idType, idInfo, idName, isExportedId, 
23                           idSpecialisation, idUnique, isDataConWrapId,
24                           mkVanillaGlobal, isLocalId, isRecordSelector,
25                           setIdUnfolding, hasNoBinding, mkUserLocal,
26                           idNewDemandInfo, setIdNewDemandInfo
27                         ) 
28 import IdInfo           {- loads of stuff -}
29 import NewDemand        ( isBottomingSig, topSig, isStrictDmd )
30 import Name             ( getOccName, nameOccName, globaliseName, setNameOcc, 
31                           localiseName, isGlobalName, setNameUnique
32                         )
33 import NameEnv          ( filterNameEnv )
34 import OccName          ( TidyOccEnv, initTidyOccEnv, tidyOccName )
35 import Type             ( tidyTopType, tidyType, tidyTyVar )
36 import Module           ( Module, moduleName )
37 import HscTypes         ( PersistentCompilerState( pcs_PRS ), 
38                           PersistentRenamerState( prsOrig ),
39                           NameSupply( nsNames, nsUniqs ),
40                           TypeEnv, extendTypeEnvList, 
41                           ModDetails(..), TyThing(..)
42                         )
43 import FiniteMap        ( lookupFM, addToFM )
44 import Maybes           ( maybeToBool, orElse )
45 import ErrUtils         ( showPass )
46 import SrcLoc           ( noSrcLoc )
47 import UniqFM           ( mapUFM )
48 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
49 import List             ( partition )
50 import Util             ( mapAccumL )
51 import Outputable
52 \end{code}
53
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection{What goes on}
59 %*                                                                      * 
60 %************************************************************************
61
62 [SLPJ: 19 Nov 00]
63
64 The plan is this.  
65
66 Step 1: Figure out external Ids
67 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68 First we figure out which Ids are "external" Ids.  An
69 "external" Id is one that is visible from outside the compilation
70 unit.  These are
71         a) the user exported ones
72         b) ones mentioned in the unfoldings, workers, 
73            or rules of externally-visible ones 
74 This exercise takes a sweep of the bindings bottom to top.  Actually,
75 in Step 2 we're also going to need to know which Ids should be
76 exported with their unfoldings, so we produce not an IdSet but an
77 IdEnv Bool
78
79
80 Step 2: Tidy the program
81 ~~~~~~~~~~~~~~~~~~~~~~~~
82 Next we traverse the bindings top to bottom.  For each *top-level*
83 binder
84
85  1. Make it into a GlobalId
86
87  2. Give it a system-wide Unique.
88     [Even non-exported things need system-wide Uniques because the
89     byte-code generator builds a single Name->BCO symbol table.]
90
91     We use the NameSupply kept in the PersistentRenamerState as the
92     source of such system-wide uniques.
93
94     For external Ids, use the original-name cache in the NameSupply 
95     to ensure that the unique assigned is the same as the Id had 
96     in any previous compilation run.
97   
98  3. If it's an external Id, make it have a global Name, otherwise
99     make it have a local Name.
100     This is used by the code generator to decide whether
101     to make the label externally visible
102
103  4. Give external Ids a "tidy" occurrence name.  This means
104     we can print them in interface files without confusing 
105     "x" (unique 5) with "x" (unique 10).
106   
107  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
108         * Its IdDetails becomes VanillaGlobal, reflecting the fact that
109           from now on we regard it as a global, not local, Id
110
111         * its unfolding, if it should have one
112         
113         * its arity, computed from the number of visible lambdas
114
115         * its CAF info, computed from what is free in its RHS
116
117                 
118 Finally, substitute these new top-level binders consistently
119 throughout, including in unfoldings.  We also tidy binders in
120 RHSs, so that they print nicely in interfaces.
121
122 \begin{code}
123 tidyCorePgm :: DynFlags -> Module
124             -> PersistentCompilerState
125             -> CgInfoEnv                -- Information from the back end,
126                                         -- to be splatted into the IdInfo
127             -> ModDetails
128             -> IO (PersistentCompilerState, ModDetails)
129
130 tidyCorePgm dflags mod pcs cg_info_env
131             (ModDetails { md_types = env_tc, md_insts = insts_tc, 
132                           md_binds = binds_in, md_rules = orphans_in })
133   = do  { showPass dflags "Tidy Core"
134
135         ; let ext_ids   = findExternalSet   binds_in orphans_in
136         ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
137
138         -- We also make sure to avoid any exported binders.  Consider
139         --      f{-u1-} = 1     -- Local decl
140         --      ...
141         --      f{-u2-} = 2     -- Exported decl
142         --
143         -- The second exported decl must 'get' the name 'f', so we
144         -- have to put 'f' in the avoids list before we get to the first
145         -- decl.  tidyTopId then does a no-op on exported binders.
146         ; let   prs           = pcs_PRS pcs
147                 orig_ns       = prsOrig prs
148
149                 init_tidy_env = (orig_ns, initTidyOccEnv avoids, emptyVarEnv)
150                 avoids        = [getOccName bndr | bndr <- bindersOfBinds binds_in,
151                                                    isGlobalName (idName bndr)]
152
153         ; let ((orig_ns', occ_env, subst_env), tidy_binds) 
154                         = mapAccumL (tidyTopBind mod ext_ids cg_info_env) 
155                                     init_tidy_env binds_in
156
157         ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
158
159         ; let prs' = prs { prsOrig = orig_ns' }
160               pcs' = pcs { pcs_PRS = prs' }
161
162         ; let final_ids  = [ id | bind <- tidy_binds
163                            , id <- bindersOf bind
164                            , isGlobalName (idName id)]
165
166                 -- Dfuns are local Ids that might have
167                 -- changed their unique during tidying
168         ; let lookup_dfun_id id = lookupVarEnv subst_env id `orElse` 
169                                   pprPanic "lookup_dfun_id" (ppr id)
170
171
172         ; let tidy_type_env = mkFinalTypeEnv env_tc final_ids
173               tidy_dfun_ids = map lookup_dfun_id insts_tc
174
175         ; let tidy_details = ModDetails { md_types = tidy_type_env,
176                                           md_rules = tidy_rules,
177                                           md_insts = tidy_dfun_ids,
178                                           md_binds = tidy_binds }
179
180         ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
181
182         ; return (pcs', tidy_details)
183         }
184
185 tidyCoreExpr :: CoreExpr -> IO CoreExpr
186 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
187 \end{code}
188
189
190 %************************************************************************
191 %*                                                                      *
192 \subsection{Write a new interface file}
193 %*                                                                      *
194 %************************************************************************
195
196 \begin{code}
197 mkFinalTypeEnv :: TypeEnv       -- From typechecker
198                -> [Id]          -- Final Ids
199                -> TypeEnv
200
201 mkFinalTypeEnv type_env final_ids
202   = extendTypeEnvList (filterNameEnv keep_it type_env)
203                       (map AnId final_ids)
204   where
205         -- The competed type environment is gotten from
206         --      a) keeping the types and classes
207         --      b) removing all Ids, 
208         --      c) adding Ids with correct IdInfo, including unfoldings,
209         --              gotten from the bindings
210         -- From (c) we keep only those Ids with Global names;
211         --          the CoreTidy pass makes sure these are all and only
212         --          the externally-accessible ones
213         -- This truncates the type environment to include only the 
214         -- exported Ids and things needed from them, which saves space
215         --
216         -- However, we do keep things like constructors, which should not appear 
217         -- in interface files, because they are needed by importing modules when
218         -- using the compilation manager
219
220         -- We keep "hasNoBinding" Ids, notably constructor workers, 
221         -- because they won't appear in the bindings from which final_ids are derived!
222     keep_it (AnId id) = hasNoBinding id -- Remove all Ids except constructor workers
223     keep_it other     = True            -- Keep all TyCons and Classes
224 \end{code}
225
226 \begin{code}
227 findExternalRules :: [CoreBind]
228                   -> [IdCoreRule] -- Orphan rules
229                   -> IdEnv a      -- Ids that are exported, so we need their rules
230                   -> [IdCoreRule]
231   -- The complete rules are gotten by combining
232   --    a) the orphan rules
233   --    b) rules embedded in the top-level Ids
234 findExternalRules binds orphan_rules ext_ids
235   | opt_OmitInterfacePragmas = []
236   | otherwise
237   = orphan_rules ++ local_rules
238   where
239     local_rules  = [ (id, rule)
240                    | id <- bindersOfBinds binds,
241                      id `elemVarEnv` ext_ids,
242                      rule <- rulesRules (idSpecialisation id),
243                      not (isBuiltinRule rule)
244                         -- We can't print builtin rules in interface files
245                         -- Since they are built in, an importing module
246                         -- will have access to them anyway
247                  ]
248 \end{code}
249
250 %************************************************************************
251 %*                                                                      *
252 \subsection{Step 1: finding externals}
253 %*                                                                      * 
254 %************************************************************************
255
256 \begin{code}
257 findExternalSet :: [CoreBind] -> [IdCoreRule]
258                 -> IdEnv Bool   -- In domain => external
259                                 -- Range = True <=> show unfolding
260         -- Step 1 from the notes above
261 findExternalSet binds orphan_rules
262   = foldr find init_needed binds
263   where
264     orphan_rule_ids :: IdSet
265     orphan_rule_ids = unionVarSets [ ruleSomeFreeVars isLocalId rule 
266                                    | (_, rule) <- orphan_rules]
267     init_needed :: IdEnv Bool
268     init_needed = mapUFM (\_ -> False) orphan_rule_ids
269         -- The mapUFM is a bit cheesy.  It is a cheap way
270         -- to turn the set of orphan_rule_ids, which we use to initialise
271         -- the sweep, into a mapping saying 'don't expose unfolding'    
272         -- (When we come to the binding site we may change our mind, of course.)
273
274     find (NonRec id rhs) needed
275         | need_id needed id = addExternal (id,rhs) needed
276         | otherwise         = needed
277     find (Rec prs) needed   = find_prs prs needed
278
279         -- For a recursive group we have to look for a fixed point
280     find_prs prs needed 
281         | null needed_prs = needed
282         | otherwise       = find_prs other_prs new_needed
283         where
284           (needed_prs, other_prs) = partition (need_pr needed) prs
285           new_needed = foldr addExternal needed needed_prs
286
287         -- The 'needed' set contains the Ids that are needed by earlier
288         -- interface file emissions.  If the Id isn't in this set, and isn't
289         -- exported, there's no need to emit anything
290     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
291     need_pr needed_set (id,rhs) = need_id needed_set id
292
293 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
294 -- The Id is needed; extend the needed set
295 -- with it and its dependents (free vars etc)
296 addExternal (id,rhs) needed
297   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
298                  id show_unfold
299   where
300     add_occ id needed = extendVarEnv needed id False
301         -- "False" because we don't know we need the Id's unfolding
302         -- We'll override it later when we find the binding site
303
304     new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
305                    | otherwise                = worker_ids      `unionVarSet`
306                                                 unfold_ids      `unionVarSet`
307                                                 spec_ids
308
309     idinfo         = idInfo id
310     dont_inline    = isNeverInlinePrag (inlinePragInfo idinfo)
311     loop_breaker   = isLoopBreaker (occInfo idinfo)
312     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
313     spec_ids       = rulesRhsFreeVars (specInfo idinfo)
314     worker_info    = workerInfo idinfo
315
316         -- Stuff to do with the Id's unfolding
317         -- The simplifier has put an up-to-date unfolding
318         -- in the IdInfo, but the RHS will do just as well
319     unfolding    = unfoldingInfo idinfo
320     rhs_is_small = not (neverUnfold unfolding)
321
322         -- We leave the unfolding there even if there is a worker
323         -- In GHCI the unfolding is used by importers
324         -- When writing an interface file, we omit the unfolding 
325         -- if there is a worker
326     show_unfold = not bottoming_fn       &&     -- Not necessary
327                   not dont_inline        &&
328                   not loop_breaker       &&
329                   rhs_is_small           &&     -- Small enough
330                   okToUnfoldInHiFile rhs        -- No casms etc
331
332     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
333                | otherwise   = emptyVarSet
334
335     worker_ids = case worker_info of
336                    HasWorker work_id _ -> unitVarSet work_id
337                    otherwise           -> emptyVarSet
338 \end{code}
339
340
341 %************************************************************************
342 %*                                                                      *
343 \subsection{Step 2: top-level tidying}
344 %*                                                                      *
345 %************************************************************************
346
347
348 \begin{code}
349 type TopTidyEnv = (NameSupply, TidyOccEnv, VarEnv Var)
350
351 -- TopTidyEnv: when tidying we need to know
352 --   * ns: The NameSupply, containing a unique supply and any pre-ordained Names.  
353 --        These may have arisen because the
354 --        renamer read in an interface file mentioning M.$wf, say,
355 --        and assigned it unique r77.  If, on this compilation, we've
356 --        invented an Id whose name is $wf (but with a different unique)
357 --        we want to rename it to have unique r77, so that we can do easy
358 --        comparisons with stuff from the interface file
359 --
360 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
361 --     are 'used'
362 --
363 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
364 \end{code}
365
366
367 \begin{code}
368 tidyTopBind :: Module
369             -> IdEnv Bool       -- Domain = Ids that should be external
370                                 -- True <=> their unfolding is external too
371             -> CgInfoEnv
372             -> TopTidyEnv -> CoreBind
373             -> (TopTidyEnv, CoreBind)
374
375 tidyTopBind mod ext_ids cg_info_env top_tidy_env (NonRec bndr rhs)
376   = ((orig,occ,subst) , NonRec bndr' rhs')
377   where
378     ((orig,occ,subst), bndr')
379          = tidyTopBinder mod ext_ids cg_info_env rec_tidy_env rhs' top_tidy_env bndr
380     rec_tidy_env = (occ,subst)
381     rhs' = tidyExpr rec_tidy_env rhs
382
383 tidyTopBind mod ext_ids cg_info_env top_tidy_env (Rec prs)
384   = (final_env, Rec prs')
385   where
386     (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
387     rec_tidy_env = (occ,subst)
388
389     do_one top_tidy_env (bndr,rhs) 
390         = ((orig,occ,subst), (bndr',rhs'))
391         where
392         ((orig,occ,subst), bndr')
393            = tidyTopBinder mod ext_ids cg_info_env 
394                 rec_tidy_env rhs' top_tidy_env bndr
395
396         rhs' = tidyExpr rec_tidy_env rhs
397
398 tidyTopBinder :: Module -> IdEnv Bool
399               -> CgInfoEnv
400               -> TidyEnv -> CoreExpr
401                         -- The TidyEnv is used to tidy the IdInfo
402                         -- The expr is the already-tided RHS
403                         -- Both are knot-tied: don't look at them!
404               -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
405   -- NB: tidyTopBinder doesn't affect the unique supply
406
407 tidyTopBinder mod ext_ids cg_info_env tidy_env rhs
408               env@(ns2, occ_env2, subst_env2) id
409
410   | isDataConWrapId id  -- Don't tidy constructor wrappers
411   = (env, id)           -- The Id is stored in the TyCon, so it would be bad
412                         -- if anything changed
413
414 -- HACK ALERT: we *do* tidy record selectors.  Reason: they mention error
415 -- messages, which may be floated out:
416 --      x_field pt = case pt of
417 --                      Rect x y -> y
418 --                      Pol _ _  -> error "buggle wuggle"
419 -- The error message will be floated out so we'll get
420 --      lvl5 = error "buggle wuggle"
421 --      x_field pt = case pt of
422 --                      Rect x y -> y
423 --                      Pol _ _  -> lvl5
424 --
425 -- When this happens, it's vital that the Id exposed to importing modules
426 -- (by ghci) mentions lvl5 in its unfolding, not the un-tidied version.
427 -- 
428 -- What about the Id in the TyCon?  It probably shouldn't be in the TyCon at
429 -- all, but in any case it will have the error message inline so it won't matter.
430
431
432   | isRecordSelector id -- We can't use the "otherwise" case, because that
433                         -- forgets the IdDetails, which forgets that this is
434                         -- a record selector, which confuses an importing module
435   = (env, id `setIdUnfolding` unfold_info)
436
437   | otherwise
438         -- This function is the heart of Step 2
439         -- The second env is the one to use for the IdInfo
440         -- It's necessary because when we are dealing with a recursive
441         -- group, a variable late in the group might be mentioned
442         -- in the IdInfo of one early in the group
443
444         -- The rhs is already tidied
445         
446   = ((orig_env', occ_env', subst_env'), id')
447   where
448     (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
449                                                is_external
450                                                (idName id)
451     ty'     = tidyTopType (idType id)
452     cg_info = lookupCgInfo cg_info_env name'
453     idinfo' = tidyIdInfo tidy_env is_external unfold_info cg_info id
454
455     id'        = mkVanillaGlobal name' ty' idinfo'
456     subst_env' = extendVarEnv subst_env2 id id'
457
458     maybe_external = lookupVarEnv ext_ids id
459     is_external    = maybeToBool maybe_external
460
461     -- Expose an unfolding if ext_ids tells us to
462     show_unfold = maybe_external `orElse` False
463     unfold_info | show_unfold = mkTopUnfolding rhs
464                 | otherwise   = noUnfolding
465
466
467 tidyIdInfo tidy_env is_external unfold_info cg_info id
468   | opt_OmitInterfacePragmas || not is_external
469         -- No IdInfo if the Id isn't external, or if we don't have -O
470   = vanillaIdInfo 
471         `setCgInfo`            cg_info
472         `setNewStrictnessInfo` newStrictnessInfo core_idinfo
473         -- Keep strictness; it's used by CorePrep
474
475   | otherwise
476   =  vanillaIdInfo 
477         `setCgInfo`            cg_info
478         `setNewStrictnessInfo` newStrictnessInfo core_idinfo
479         `setInlinePragInfo`    inlinePragInfo core_idinfo
480         `setUnfoldingInfo`     unfold_info
481         `setWorkerInfo`        tidyWorker tidy_env (workerInfo core_idinfo)
482         -- NB: we throw away the Rules
483         -- They have already been extracted by findExternalRules
484   where
485     core_idinfo = idInfo id
486
487
488 -- This is where we set names to local/global based on whether they really are 
489 -- externally visible (see comment at the top of this module).  If the name
490 -- was previously local, we have to give it a unique occurrence name if
491 -- we intend to globalise it.
492 tidyTopName mod ns occ_env external name
493   | global && internal = (ns, occ_env, localiseName name)
494
495   | global && external = (ns, occ_env, name)
496         -- Global names are assumed to have been allocated by the renamer,
497         -- so they already have the "right" unique
498         -- And it's a system-wide unique too
499
500   | local  && internal = (ns { nsUniqs = us2 }, occ_env', unique_name)
501         -- Even local, internal names must get a unique occurrence, because
502         -- if we do -split-objs we globalise the name later, in the code generator
503         --
504         -- Similarly, we must make sure it has a system-wide Unique, because
505         -- the byte-code generator builds a system-wide Name->BCO symbol table
506
507   | local  && external = case lookupFM ns_names key of
508                            Just orig -> (ns,                                        occ_env', orig)
509                            Nothing   -> (ns { nsUniqs = us2, nsNames = ns_names' }, occ_env', global_name)
510         -- If we want to globalise a currently-local name, check
511         -- whether we have already assigned a unique for it.
512         -- If so, use it; if not, extend the table
513
514   where
515     global           = isGlobalName name
516     local            = not global
517     internal         = not external
518
519     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
520     key              = (moduleName mod, occ')
521     ns_names         = nsNames ns
522     ns_uniqs         = nsUniqs ns
523     (us1, us2)       = splitUniqSupply ns_uniqs
524     unique_name      = setNameUnique (setNameOcc name occ') (uniqFromSupply us1)
525     global_name      = globaliseName unique_name mod
526     ns_names'        = addToFM ns_names key global_name
527
528
529 ------------  Worker  --------------
530 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
531   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
532 tidyWorker tidy_env other
533   = NoWorker
534
535 ------------  Rules  --------------
536 tidyIdRules :: TidyEnv -> [IdCoreRule] -> [IdCoreRule]
537 tidyIdRules env [] = []
538 tidyIdRules env ((fn,rule) : rules)
539   = tidyRule env rule           =: \ rule ->
540     tidyIdRules env rules       =: \ rules ->
541      ((tidyVarOcc env fn, rule) : rules)
542
543 tidyRule :: TidyEnv -> CoreRule -> CoreRule
544 tidyRule env rule@(BuiltinRule _) = rule
545 tidyRule env (Rule name vars tpl_args rhs)
546   = tidyBndrs env vars                  =: \ (env', vars) ->
547     map (tidyExpr env') tpl_args        =: \ tpl_args ->
548      (Rule name vars tpl_args (tidyExpr env' rhs))
549 \end{code}
550
551 %************************************************************************
552 %*                                                                      *
553 \subsection{Step 2: inner tidying
554 %*                                                                      *
555 %************************************************************************
556
557 \begin{code}
558 tidyBind :: TidyEnv
559          -> CoreBind
560          ->  (TidyEnv, CoreBind)
561
562 tidyBind env (NonRec bndr rhs)
563   = tidyBndrWithRhs env (bndr,rhs) =: \ (env', bndr') ->
564     (env', NonRec bndr' (tidyExpr env' rhs))
565
566 tidyBind env (Rec prs)
567   = mapAccumL tidyBndrWithRhs env prs   =: \ (env', bndrs') ->
568     map (tidyExpr env') (map snd prs)   =: \ rhss' ->
569     (env', Rec (zip bndrs' rhss'))
570
571
572 tidyExpr env (Var v)    =  Var (tidyVarOcc env v)
573 tidyExpr env (Type ty)  =  Type (tidyType env ty)
574 tidyExpr env (Lit lit)  =  Lit lit
575 tidyExpr env (App f a)  =  App (tidyExpr env f) (tidyExpr env a)
576 tidyExpr env (Note n e) =  Note (tidyNote env n) (tidyExpr env e)
577
578 tidyExpr env (Let b e) 
579   = tidyBind env b      =: \ (env', b') ->
580     Let b' (tidyExpr env' e)
581
582 tidyExpr env (Case e b alts)
583   = tidyBndr env b      =: \ (env', b) ->
584     Case (tidyExpr env e) b (map (tidyAlt env') alts)
585
586 tidyExpr env (Lam b e)
587   = tidyBndr env b      =: \ (env', b) ->
588     Lam b (tidyExpr env' e)
589
590
591 tidyAlt env (con, vs, rhs)
592   = tidyBndrs env vs    =: \ (env', vs) ->
593     (con, vs, tidyExpr env' rhs)
594
595 tidyNote env (Coerce t1 t2)  = Coerce (tidyType env t1) (tidyType env t2)
596 tidyNote env note            = note
597 \end{code}
598
599
600 %************************************************************************
601 %*                                                                      *
602 \subsection{Tidying up non-top-level binders}
603 %*                                                                      *
604 %************************************************************************
605
606 \begin{code}
607 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
608                                   Just v' -> v'
609                                   Nothing -> v
610
611 -- tidyBndr is used for lambda and case binders
612 tidyBndr :: TidyEnv -> Var -> (TidyEnv, Var)
613 tidyBndr env var
614   | isTyVar var = tidyTyVar env var
615   | otherwise   = tidyId env var
616
617 tidyBndrs :: TidyEnv -> [Var] -> (TidyEnv, [Var])
618 tidyBndrs env vars = mapAccumL tidyBndr env vars
619
620 -- tidyBndrWithRhs is used for let binders
621 tidyBndrWithRhs :: TidyEnv -> (Id, CoreExpr) -> (TidyEnv, Var)
622 tidyBndrWithRhs env (id,rhs) 
623   = add_dmd_info (tidyId env id)
624   where
625         -- We add demand info for let(rec) binders, because
626         -- that's what tells CorePrep to generate a case instead of a thunk
627     add_dmd_info (env,new_id) 
628         | isStrictDmd dmd_info = (env, setIdNewDemandInfo new_id dmd_info)
629         | otherwise            = (env, new_id)
630     dmd_info = idNewDemandInfo id
631
632 tidyId :: TidyEnv -> Id -> (TidyEnv, Id)
633 tidyId env@(tidy_env, var_env) id
634   =     -- Non-top-level variables
635     let 
636         -- Give the Id a fresh print-name, *and* rename its type
637         -- The SrcLoc isn't important now, 
638         -- though we could extract it from the Id
639         -- 
640         -- All local Ids now have the same IdInfo, which should save some
641         -- space.
642         (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
643         ty'               = tidyType (tidy_env,var_env) (idType id)
644         id'               = mkUserLocal occ' (idUnique id) ty' noSrcLoc
645         var_env'          = extendVarEnv var_env id id'
646     in
647      ((tidy_env', var_env'), id')
648 \end{code}
649
650 \begin{code}
651 m =: k = m `seq` k m
652 \end{code}