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