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