1 -----------------------------------------------------------------------------
3 -- GHCi Interactive debugging commands
5 -- Pepe Iborra (supported by Google SoC) 2006
7 -- ToDo: lots of violation of layering here. This module should
8 -- decide whether it is above the GHC API (import GHC and nothing
11 -----------------------------------------------------------------------------
13 module Debugger (pprintClosureCommand) where
16 import RtClosureInspect
22 import Var hiding ( varName )
33 import Pretty ( Mode(..), showDocWith )
37 import Control.Exception
46 #include "HsVersions.h"
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))
57 substs <- catMaybes `liftM` mapM (go session)
58 [id | AnId id <- tythings]
59 mapM (applySubstToEnv session . skolemSubst) substs
63 -- Do the obtainTerm--bindSuspensions-computeSubstitution dance
64 go :: Session -> Id -> IO (Maybe TvSubst)
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
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]
89 ASSERT2 (isJust mb_subst, ppr reconstructed_type $$ (ppr$ idType id))
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 subst_dom= varEnvKeys$ getTvSubstEnv subst
103 subst_ran= varEnvElts$ getTvSubstEnv subst
104 new_tvs = [ tv | t <- subst_ran, let Just tv = getTyVar_maybe t]
105 ic_tyvars'= (`delVarSetListByKey` subst_dom)
106 . (`extendVarSetList` new_tvs)
108 ictxt' = ictxt { ic_type_env = type_env'
109 , ic_tyvars = ic_tyvars' }
110 writeIORef ref (hsc_env {hsc_IC = ictxt'})
112 where delVarSetListByKey = foldl' delVarSetByKey
114 tidyTermTyVars :: Session -> Term -> IO Term
115 tidyTermTyVars (Session ref) t = do
116 hsc_env <- readIORef ref
117 let env_tvs = ic_tyvars (hsc_IC hsc_env)
118 my_tvs = termTyVars t
119 tvs = env_tvs `minusVarSet` my_tvs
120 tyvarOccName = nameOccName . tyVarName
121 tidyEnv = (initTidyOccEnv (map tyvarOccName (varSetElems tvs))
122 , env_tvs `intersectVarSet` my_tvs)
123 return$ mapTermType (snd . tidyOpenType tidyEnv) t
125 -- | Give names, and bind in the interactive environment, to all the suspensions
126 -- included (inductively) in a term
127 bindSuspensions :: Session -> Term -> IO Term
128 bindSuspensions cms@(Session ref) t = do
129 hsc_env <- readIORef ref
130 inScope <- GHC.getBindings cms
131 let ictxt = hsc_IC hsc_env
132 type_env = ic_type_env ictxt
134 alreadyUsedNames = map (occNameString . nameOccName . getName) inScope
135 availNames = map ((prefix++) . show) [1..] \\ alreadyUsedNames
136 availNames_var <- newIORef availNames
137 (t', stuff) <- foldTerm (nameSuspensionsAndGetInfos availNames_var) t
138 let (names, tys, hvals) = unzip3 stuff
139 let tys' = map mk_skol_ty tys
140 let ids = [ mkGlobalId VanillaGlobal name ty vanillaIdInfo
141 | (name,ty) <- zip names tys']
142 new_tyvars = tyVarsOfTypes tys'
143 new_type_env = extendTypeEnvWithIds type_env ids
144 old_tyvars = ic_tyvars ictxt
145 new_ic = ictxt { ic_type_env = new_type_env,
146 ic_tyvars = old_tyvars `unionVarSet` new_tyvars }
147 extendLinkEnv (zip names hvals)
148 writeIORef ref (hsc_env {hsc_IC = new_ic })
152 -- Processing suspensions. Give names and recopilate info
153 nameSuspensionsAndGetInfos :: IORef [String] -> TermFold (IO (Term, [(Name,Type,HValue)]))
154 nameSuspensionsAndGetInfos freeNames = TermFold
156 fSuspension = doSuspension freeNames
157 , fTerm = \ty dc v tt -> do
159 let (terms,names) = unzip tt'
160 return (Term ty dc v terms, concat names)
161 , fPrim = \ty n ->return (Prim ty n,[])
163 doSuspension freeNames ct mb_ty hval Nothing = do
164 name <- atomicModifyIORef freeNames (\x->(tail x, head x))
165 n <- newGrimName cms name
166 let ty' = fromMaybe (error "unexpected") mb_ty
167 return (Suspension ct mb_ty hval (Just n), [(n,ty',hval)])
170 -- A custom Term printer to enable the use of Show instances
171 printTerm cms@(Session ref) = cPprTerm cPpr
173 cPpr = \p-> cPprShowable : cPprTermBase p
174 cPprShowable prec t@Term{ty=ty, dc=dc, val=val} = do
175 let hasType = isEmptyVarSet (tyVarsOfType ty) -- redundant
176 isEvaled = isFullyEvaluatedTerm t
177 if not isEvaled -- || not hasType
180 hsc_env <- readIORef ref
181 dflags <- GHC.getSessionDynFlags cms
183 (new_env, bname) <- bindToFreshName hsc_env ty "showme"
184 writeIORef ref (new_env)
185 let noop_log _ _ _ _ = return ()
186 expr = "show " ++ showSDoc (ppr bname)
187 GHC.setSessionDynFlags cms dflags{log_action=noop_log}
188 mb_txt <- withExtendedLinkEnv [(bname, val)]
189 (GHC.compileExpr cms expr)
190 let myprec = 9 -- TODO Infix constructors
192 Just txt -> return . Just . text . unsafeCoerce#
194 Nothing -> return Nothing
196 writeIORef ref hsc_env
197 GHC.setSessionDynFlags cms dflags
199 bindToFreshName hsc_env ty userName = do
200 name <- newGrimName cms userName
201 let ictxt = hsc_IC hsc_env
202 type_env = ic_type_env ictxt
203 id = mkGlobalId VanillaGlobal name ty vanillaIdInfo
204 new_type_env = extendTypeEnv type_env (AnId id)
205 new_ic = ictxt { ic_type_env = new_type_env }
206 return (hsc_env {hsc_IC = new_ic }, name)
208 -- Create new uniques and give them sequentially numbered names
209 -- newGrimName :: Session -> String -> IO Name
210 newGrimName cms userName = do
211 us <- mkSplitUniqSupply 'b'
212 let unique = uniqFromSupply us
213 occname = mkOccName varName userName
214 name = mkInternalName unique occname noSrcLoc
217 skolemSubst subst = subst `setTvSubstEnv`
218 mapVarEnv mk_skol_ty (getTvSubstEnv subst)
219 mk_skol_ty ty | tyvars <- varSetElems (tyVarsOfType ty)
220 , tyvars' <- map (mkTyVarTy . mk_skol_tv) tyvars
221 = substTyWith tyvars tyvars' ty
222 mk_skol_tv tv = mkTcTyVar (tyVarName tv) (tyVarKind tv)
223 (SkolemTv RuntimeUnkSkol)