Restore tidying up of tyvars in :print
[ghc-hetmet.git] / compiler / ghci / Debugger.hs
1 -----------------------------------------------------------------------------
2 --
3 -- GHCi Interactive debugging commands 
4 --
5 -- Pepe Iborra (supported by Google SoC) 2006
6 --
7 -- ToDo: lots of violation of layering here.  This module should
8 -- decide whether it is above the GHC API (import GHC and nothing
9 -- else) or below it.
10 -- 
11 -----------------------------------------------------------------------------
12
13 module Debugger (pprintClosureCommand) where
14
15 import Linker
16 import RtClosureInspect
17
18 import HscTypes
19 import IdInfo
20 --import Id
21 import Name
22 import Var hiding ( varName )
23 import VarSet
24 import VarEnv
25 import Name 
26 import UniqSupply
27 import Type
28 import TcType
29 import TcGadt
30 import GHC
31
32 import Outputable
33 import Pretty                    ( Mode(..), showDocWith )
34 import FastString
35 import SrcLoc
36
37 import Control.Exception
38 import Control.Monad
39 import Data.List
40 import Data.Maybe
41 import Data.IORef
42
43 import System.IO
44 import GHC.Exts
45
46 #include "HsVersions.h"
47
48 -------------------------------------
49 -- | The :print & friends commands
50 -------------------------------------
51 pprintClosureCommand :: Session -> Bool -> Bool -> String -> IO ()
52 pprintClosureCommand session bindThings force str = do 
53   tythings <- (catMaybes . concat) `liftM`
54                  mapM (\w -> GHC.parseName session w >>= 
55                                 mapM (GHC.lookupName session))
56                       (words str)
57   substs <- catMaybes `liftM` mapM (go session) 
58                                    [id | AnId id <- tythings]
59   mapM (applySubstToEnv session . skolemSubst) substs
60   return ()
61  where 
62
63    -- Do the obtainTerm--bindSuspensions-computeSubstitution dance
64    go :: Session -> Id -> IO (Maybe TvSubst)
65    go cms id = do 
66      mb_term <- obtainTerm cms force id 
67      maybe (return Nothing) `flip` mb_term $ \term_ -> do
68        term      <- tidyTermTyVars cms term_
69        term'     <- if not bindThings then return term 
70                      else bindSuspensions cms term                         
71        showterm  <- printTerm cms term'
72        unqual    <- GHC.getPrintUnqual cms
73        let showSDocForUserOneLine unqual doc = 
74                showDocWith LeftMode (doc (mkErrStyle unqual))
75        (putStrLn . showSDocForUserOneLine unqual) (ppr id <+> char '=' <+> showterm)
76      -- Before leaving, we compare the type obtained to see if it's more specific
77      --  Then, we extract a substitution, 
78      --  mapping the old tyvars to the reconstructed types.
79        let Just reconstructed_type = termType term
80
81      -- tcUnifyTys doesn't look through forall's, so we drop them from 
82      -- the original type, instead of sigma-typing the reconstructed type
83      -- In addition, we strip newtypes too, since the reconstructed type might
84      --   not have recovered them all
85            mb_subst = tcUnifyTys (const BindMe) 
86                                  [repType' $ dropForAlls$ idType id] 
87                                  [repType' $ reconstructed_type]  
88
89        ASSERT2 (isJust mb_subst, ppr reconstructed_type $$ (ppr$ idType id)) 
90         return mb_subst
91
92    applySubstToEnv :: Session -> TvSubst -> IO ()
93    applySubstToEnv cms subst | isEmptyTvSubst subst = return ()
94    applySubstToEnv cms@(Session ref) subst = do
95       hsc_env <- readIORef ref
96       inScope <- GHC.getBindings cms
97       let ictxt    = hsc_IC hsc_env
98           type_env = ic_type_env ictxt
99           ids      = typeEnvIds type_env
100           ids'     = map (\id -> id `setIdType` substTy subst (idType id)) ids
101           type_env'= extendTypeEnvWithIds type_env ids'
102           ictxt'   = ictxt { ic_type_env = type_env' }
103       writeIORef ref (hsc_env {hsc_IC = ictxt'})
104
105    tidyTermTyVars :: Session -> Term -> IO Term
106    tidyTermTyVars (Session ref) t = do
107      hsc_env <- readIORef ref
108      let env_tvs      = ic_tyvars (hsc_IC hsc_env)
109          my_tvs       = termTyVars t
110          tvs          = env_tvs `minusVarSet` my_tvs
111          tyvarOccName = nameOccName . tyVarName 
112          tidyEnv      = (initTidyOccEnv (map tyvarOccName (varSetElems tvs))
113                         , env_tvs `intersectVarSet` my_tvs)
114      return$ mapTermType (snd . tidyOpenType tidyEnv) t
115
116 -- | Give names, and bind in the interactive environment, to all the suspensions
117 --   included (inductively) in a term
118 bindSuspensions :: Session -> Term -> IO Term
119 bindSuspensions cms@(Session ref) t = do 
120       hsc_env <- readIORef ref
121       inScope <- GHC.getBindings cms
122       let ictxt        = hsc_IC hsc_env
123           type_env     = ic_type_env ictxt
124           prefix       = "_t"
125           alreadyUsedNames = map (occNameString . nameOccName . getName) inScope
126           availNames   = map ((prefix++) . show) [1..] \\ alreadyUsedNames 
127       availNames_var  <- newIORef availNames
128       (t', stuff)     <- foldTerm (nameSuspensionsAndGetInfos availNames_var) t
129       let (names, tys, hvals) = unzip3 stuff
130       let tys' = map mk_skol_ty tys
131       let ids = [ mkGlobalId VanillaGlobal name ty vanillaIdInfo
132                 | (name,ty) <- zip names tys']
133           new_tyvars   = tyVarsOfTypes tys'
134           new_type_env = extendTypeEnvWithIds type_env ids 
135           old_tyvars   = ic_tyvars ictxt
136           new_ic       = ictxt { ic_type_env = new_type_env,
137                                  ic_tyvars   = old_tyvars `unionVarSet` new_tyvars }
138       extendLinkEnv (zip names hvals)
139       writeIORef ref (hsc_env {hsc_IC = new_ic })
140       return t'
141      where    
142
143 --    Processing suspensions. Give names and recopilate info
144         nameSuspensionsAndGetInfos :: IORef [String] -> TermFold (IO (Term, [(Name,Type,HValue)]))
145         nameSuspensionsAndGetInfos freeNames = TermFold 
146                       {
147                         fSuspension = doSuspension freeNames
148                       , fTerm = \ty dc v tt -> do 
149                                     tt' <- sequence tt 
150                                     let (terms,names) = unzip tt' 
151                                     return (Term ty dc v terms, concat names)
152                       , fPrim    = \ty n ->return (Prim ty n,[])
153                       }
154         doSuspension freeNames ct mb_ty hval Nothing = do
155           name <- atomicModifyIORef freeNames (\x->(tail x, head x))
156           n <- newGrimName cms name
157           let ty' = fromMaybe (error "unexpected") mb_ty
158           return (Suspension ct mb_ty hval (Just n), [(n,ty',hval)])
159
160
161 --  A custom Term printer to enable the use of Show instances
162 printTerm cms@(Session ref) = cPprTerm cPpr
163  where
164   cPpr = \p-> cPprShowable : cPprTermBase p 
165   cPprShowable prec t@Term{ty=ty, dc=dc, val=val} = do
166     let hasType = isEmptyVarSet (tyVarsOfType ty)  -- redundant
167         isEvaled = isFullyEvaluatedTerm t
168     if not isEvaled -- || not hasType
169      then return Nothing
170      else do 
171         hsc_env <- readIORef ref
172         dflags  <- GHC.getSessionDynFlags cms
173         do
174            (new_env, bname) <- bindToFreshName hsc_env ty "showme"
175            writeIORef ref (new_env)
176            let noop_log _ _ _ _ = return () 
177                expr = "show " ++ showSDoc (ppr bname)
178            GHC.setSessionDynFlags cms dflags{log_action=noop_log}
179            mb_txt <- withExtendedLinkEnv [(bname, val)] 
180                                          (GHC.compileExpr cms expr)
181            let myprec = 9 -- TODO Infix constructors
182            case mb_txt of 
183              Just txt -> return . Just . text . unsafeCoerce# 
184                            $ txt
185              Nothing  -> return Nothing
186          `finally` do 
187            writeIORef ref hsc_env
188            GHC.setSessionDynFlags cms dflags
189      
190   bindToFreshName hsc_env ty userName = do
191     name <- newGrimName cms userName 
192     let ictxt    = hsc_IC hsc_env
193         type_env = ic_type_env ictxt
194         id       = mkGlobalId VanillaGlobal name ty vanillaIdInfo
195         new_type_env = extendTypeEnv type_env (AnId id)
196         new_ic       = ictxt { ic_type_env     = new_type_env }
197     return (hsc_env {hsc_IC = new_ic }, name)
198
199 --    Create new uniques and give them sequentially numbered names
200 --    newGrimName :: Session -> String -> IO Name
201 newGrimName cms userName  = do
202     us <- mkSplitUniqSupply 'b'
203     let unique  = uniqFromSupply us
204         occname = mkOccName varName userName
205         name    = mkInternalName unique occname noSrcLoc
206     return name
207
208 skolemSubst subst = subst `setTvSubstEnv` 
209                       mapVarEnv mk_skol_ty (getTvSubstEnv subst)
210 mk_skol_ty ty | tyvars  <- varSetElems (tyVarsOfType ty)
211               , tyvars' <- map (mkTyVarTy . mk_skol_tv) tyvars
212               = substTyWith tyvars tyvars' ty
213 mk_skol_tv tv = mkTcTyVar (tyVarName tv) (tyVarKind tv) 
214                       (SkolemTv RuntimeUnkSkol)