f662217a69f4926c8a49447835d9f590c21e70ff
[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        term_ <- obtainTerm cms force id 
67        term      <- tidyTermTyVars cms term_
68        term'     <- if not bindThings then return term 
69                      else bindSuspensions cms term                         
70        showterm  <- printTerm cms term'
71        unqual    <- GHC.getPrintUnqual cms
72        let showSDocForUserOneLine unqual doc = 
73                showDocWith LeftMode (doc (mkErrStyle unqual))
74        (putStrLn . showSDocForUserOneLine unqual) 
75                                    (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           ids      = ic_tmp_ids ictxt
99           ids'     = map (\id -> id `setIdType` substTy subst (idType id)) ids
100           subst_dom= varEnvKeys$ getTvSubstEnv subst
101           subst_ran= varEnvElts$ getTvSubstEnv subst
102           new_tvs  = [ tv | Just tv <- map getTyVar_maybe subst_ran]  
103           ic_tyvars'= (`delVarSetListByKey` subst_dom) 
104                     . (`extendVarSetList`   new_tvs)
105                         $ ic_tyvars ictxt
106           ictxt'   = ictxt { ic_tmp_ids = ids'
107                            , ic_tyvars   = ic_tyvars' }
108       writeIORef ref (hsc_env {hsc_IC = ictxt'})
109
110           where delVarSetListByKey = foldl' delVarSetByKey
111
112    tidyTermTyVars :: Session -> Term -> IO Term
113    tidyTermTyVars (Session ref) t = do
114      hsc_env <- readIORef ref
115      let env_tvs      = ic_tyvars (hsc_IC hsc_env)
116          my_tvs       = termTyVars t
117          tvs          = env_tvs `minusVarSet` my_tvs
118          tyvarOccName = nameOccName . tyVarName 
119          tidyEnv      = (initTidyOccEnv (map tyvarOccName (varSetElems tvs))
120                         , env_tvs `intersectVarSet` my_tvs)
121      return$ mapTermType (snd . tidyOpenType tidyEnv) t
122
123 -- | Give names, and bind in the interactive environment, to all the suspensions
124 --   included (inductively) in a term
125 bindSuspensions :: Session -> Term -> IO Term
126 bindSuspensions cms@(Session ref) t = do 
127       hsc_env <- readIORef ref
128       inScope <- GHC.getBindings cms
129       let ictxt        = hsc_IC hsc_env
130           prefix       = "_t"
131           alreadyUsedNames = map (occNameString . nameOccName . getName) inScope
132           availNames   = map ((prefix++) . show) [1..] \\ alreadyUsedNames 
133       availNames_var  <- newIORef availNames
134       (t', stuff)     <- foldTerm (nameSuspensionsAndGetInfos availNames_var) t
135       let (names, tys, hvals) = unzip3 stuff
136       let tys' = map mk_skol_ty tys
137       let ids = [ mkGlobalId VanillaGlobal name ty vanillaIdInfo
138                 | (name,ty) <- zip names tys']
139           new_tyvars   = tyVarsOfTypes tys'
140           new_ic       = extendInteractiveContext ictxt ids new_tyvars
141       extendLinkEnv (zip names hvals)
142       writeIORef ref (hsc_env {hsc_IC = new_ic })
143       return t'
144      where
145
146 --    Processing suspensions. Give names and recopilate info
147         nameSuspensionsAndGetInfos :: IORef [String] -> 
148                                        TermFold (IO (Term, [(Name,Type,HValue)]))
149         nameSuspensionsAndGetInfos freeNames = TermFold 
150                       {
151                         fSuspension = doSuspension freeNames
152                       , fTerm = \ty dc v tt -> do 
153                                     tt' <- sequence tt 
154                                     let (terms,names) = unzip tt' 
155                                     return (Term ty dc v terms, concat names)
156                       , fPrim    = \ty n ->return (Prim ty n,[])
157                       }
158         doSuspension freeNames ct mb_ty hval Nothing = do
159           name <- atomicModifyIORef freeNames (\x->(tail x, head x))
160           n <- newGrimName cms name
161           let ty' = fromMaybe (error "unexpected") mb_ty
162           return (Suspension ct mb_ty hval (Just n), [(n,ty',hval)])
163
164
165 --  A custom Term printer to enable the use of Show instances
166 printTerm cms@(Session ref) = cPprTerm cPpr
167  where
168   cPpr = \p-> cPprShowable : cPprTermBase p 
169   cPprShowable prec t@Term{ty=ty, dc=dc, val=val} = do
170     let hasType = isEmptyVarSet (tyVarsOfType ty)  -- redundant
171         isEvaled = isFullyEvaluatedTerm t
172     if not isEvaled -- || not hasType
173      then return Nothing
174      else do 
175         hsc_env <- readIORef ref
176         dflags  <- GHC.getSessionDynFlags cms
177         do
178            (new_env, bname) <- bindToFreshName hsc_env ty "showme"
179            writeIORef ref (new_env)
180            let noop_log _ _ _ _ = return () 
181                expr = "show " ++ showSDoc (ppr bname)
182            GHC.setSessionDynFlags cms dflags{log_action=noop_log}
183            mb_txt <- withExtendedLinkEnv [(bname, val)] 
184                                          (GHC.compileExpr cms expr)
185            let myprec = 9 -- TODO Infix constructors
186            case mb_txt of 
187              Just txt -> return . Just . text . unsafeCoerce# 
188                            $ txt
189              Nothing  -> return Nothing
190          `finally` do 
191            writeIORef ref hsc_env
192            GHC.setSessionDynFlags cms dflags
193      
194   bindToFreshName hsc_env ty userName = do
195     name <- newGrimName cms userName 
196     let ictxt    = hsc_IC hsc_env
197         tmp_ids  = ic_tmp_ids ictxt
198         id       = mkGlobalId VanillaGlobal name ty vanillaIdInfo
199         new_ic   = ictxt { ic_tmp_ids = id : tmp_ids }
200     return (hsc_env {hsc_IC = new_ic }, name)
201
202 --    Create new uniques and give them sequentially numbered names
203 --    newGrimName :: Session -> String -> IO Name
204 newGrimName cms userName  = do
205     us <- mkSplitUniqSupply 'b'
206     let unique  = uniqFromSupply us
207         occname = mkOccName varName userName
208         name    = mkInternalName unique occname noSrcSpan
209     return name
210
211 skolemSubst subst = subst `setTvSubstEnv` 
212                       mapVarEnv mk_skol_ty (getTvSubstEnv subst)
213 mk_skol_ty ty | tyvars  <- varSetElems (tyVarsOfType ty)
214               , tyvars' <- map (mkTyVarTy . mk_skol_tv) tyvars
215               = substTyWith tyvars tyvars' ty
216 mk_skol_tv tv = mkTcTyVar (tyVarName tv) (tyVarKind tv) 
217                       (SkolemTv RuntimeUnkSkol)