Fold testsuite.git into ghc.git (re #8545)
[ghc.git] / compiler / ghci / RtClosureInspect.hs
1 -----------------------------------------------------------------------------
2 --
3 -- GHC Interactive support for inspecting arbitrary closures at runtime
4 --
5 -- Pepe Iborra (supported by Google SoC) 2006
6 --
7 -----------------------------------------------------------------------------
8
9 {-# OPTIONS -fno-warn-tabs #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and
12 -- detab the module (please do the detabbing in a separate patch). See
13 -- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
14 -- for details
15
16 module RtClosureInspect(
17 cvObtainTerm, -- :: HscEnv -> Int -> Bool -> Maybe Type -> HValue -> IO Term
18 cvReconstructType,
19 improveRTTIType,
20
21 Term(..),
22 isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap,
23 isFullyEvaluated, isFullyEvaluatedTerm,
24 termType, mapTermType, termTyVars,
25 foldTerm, TermFold(..), foldTermM, TermFoldM(..), idTermFold,
26 pprTerm, cPprTerm, cPprTermBase, CustomTermPrinter,
27
28 -- unsafeDeepSeq,
29
30 Closure(..), getClosureData, ClosureType(..), isConstr, isIndirection
31 ) where
32
33 #include "HsVersions.h"
34
35 import DebuggerUtils
36 import ByteCodeItbls ( StgInfoTable, peekItbl )
37 import qualified ByteCodeItbls as BCI( StgInfoTable(..) )
38 import BasicTypes ( HValue )
39 import HscTypes
40
41 import DataCon
42 import Type
43 import qualified Unify as U
44 import Var
45 import TcRnMonad
46 import TcType
47 import TcMType
48 import TcHsSyn ( zonkTcTypeToType, mkEmptyZonkEnv )
49 import TcUnify
50 import TcEnv
51
52 import TyCon
53 import Name
54 import VarEnv
55 import Util
56 import VarSet
57 import BasicTypes ( TupleSort(UnboxedTuple) )
58 import TysPrim
59 import PrelNames
60 import TysWiredIn
61 import DynFlags
62 import Outputable as Ppr
63 import GHC.Arr ( Array(..) )
64 import GHC.Exts
65 import GHC.IO ( IO(..) )
66
67 import StaticFlags( opt_PprStyle_Debug )
68 import Control.Monad
69 import Data.Maybe
70 import Data.Array.Base
71 import Data.Ix
72 import Data.List
73 import qualified Data.Sequence as Seq
74 import Data.Monoid (mappend)
75 import Data.Sequence (viewl, ViewL(..))
76 import Foreign.Safe
77 import System.IO.Unsafe
78
79 ---------------------------------------------
80 -- * A representation of semi evaluated Terms
81 ---------------------------------------------
82
83 data Term = Term { ty :: RttiType
84 , dc :: Either String DataCon
85 -- Carries a text representation if the datacon is
86 -- not exported by the .hi file, which is the case
87 -- for private constructors in -O0 compiled libraries
88 , val :: HValue
89 , subTerms :: [Term] }
90
91 | Prim { ty :: RttiType
92 , value :: [Word] }
93
94 | Suspension { ctype :: ClosureType
95 , ty :: RttiType
96 , val :: HValue
97 , bound_to :: Maybe Name -- Useful for printing
98 }
99 | NewtypeWrap{ -- At runtime there are no newtypes, and hence no
100 -- newtype constructors. A NewtypeWrap is just a
101 -- made-up tag saying "heads up, there used to be
102 -- a newtype constructor here".
103 ty :: RttiType
104 , dc :: Either String DataCon
105 , wrapped_term :: Term }
106 | RefWrap { -- The contents of a reference
107 ty :: RttiType
108 , wrapped_term :: Term }
109
110 isTerm, isSuspension, isPrim, isFun, isFunLike, isNewtypeWrap :: Term -> Bool
111 isTerm Term{} = True
112 isTerm _ = False
113 isSuspension Suspension{} = True
114 isSuspension _ = False
115 isPrim Prim{} = True
116 isPrim _ = False
117 isNewtypeWrap NewtypeWrap{} = True
118 isNewtypeWrap _ = False
119
120 isFun Suspension{ctype=Fun} = True
121 isFun _ = False
122
123 isFunLike s@Suspension{ty=ty} = isFun s || isFunTy ty
124 isFunLike _ = False
125
126 termType :: Term -> RttiType
127 termType t = ty t
128
129 isFullyEvaluatedTerm :: Term -> Bool
130 isFullyEvaluatedTerm Term {subTerms=tt} = all isFullyEvaluatedTerm tt
131 isFullyEvaluatedTerm Prim {} = True
132 isFullyEvaluatedTerm NewtypeWrap{wrapped_term=t} = isFullyEvaluatedTerm t
133 isFullyEvaluatedTerm RefWrap{wrapped_term=t} = isFullyEvaluatedTerm t
134 isFullyEvaluatedTerm _ = False
135
136 instance Outputable (Term) where
137 ppr t | Just doc <- cPprTerm cPprTermBase t = doc
138 | otherwise = panic "Outputable Term instance"
139
140 -------------------------------------------------------------------------
141 -- Runtime Closure Datatype and functions for retrieving closure related stuff
142 -------------------------------------------------------------------------
143 data ClosureType = Constr
144 | Fun
145 | Thunk Int
146 | ThunkSelector
147 | Blackhole
148 | AP
149 | PAP
150 | Indirection Int
151 | MutVar Int
152 | MVar Int
153 | Other Int
154 deriving (Show, Eq)
155
156 data Closure = Closure { tipe :: ClosureType
157 , infoPtr :: Ptr ()
158 , infoTable :: StgInfoTable
159 , ptrs :: Array Int HValue
160 , nonPtrs :: [Word]
161 }
162
163 instance Outputable ClosureType where
164 ppr = text . show
165
166 #include "../includes/rts/storage/ClosureTypes.h"
167
168 aP_CODE, pAP_CODE :: Int
169 aP_CODE = AP
170 pAP_CODE = PAP
171 #undef AP
172 #undef PAP
173
174 getClosureData :: DynFlags -> a -> IO Closure
175 getClosureData dflags a =
176 case unpackClosure# a of
177 (# iptr, ptrs, nptrs #) -> do
178 let iptr'
179 | ghciTablesNextToCode =
180 Ptr iptr
181 | otherwise =
182 -- the info pointer we get back from unpackClosure#
183 -- is to the beginning of the standard info table,
184 -- but the Storable instance for info tables takes
185 -- into account the extra entry pointer when
186 -- !ghciTablesNextToCode, so we must adjust here:
187 Ptr iptr `plusPtr` negate (wORD_SIZE dflags)
188 itbl <- peekItbl dflags iptr'
189 let tipe = readCType (BCI.tipe itbl)
190 elems = fromIntegral (BCI.ptrs itbl)
191 ptrsList = Array 0 (elems - 1) elems ptrs
192 nptrs_data = [W# (indexWordArray# nptrs i)
193 | I# i <- [0.. fromIntegral (BCI.nptrs itbl)-1] ]
194 ASSERT(elems >= 0) return ()
195 ptrsList `seq`
196 return (Closure tipe (Ptr iptr) itbl ptrsList nptrs_data)
197
198 readCType :: Integral a => a -> ClosureType
199 readCType i
200 | i >= CONSTR && i <= CONSTR_NOCAF_STATIC = Constr
201 | i >= FUN && i <= FUN_STATIC = Fun
202 | i >= THUNK && i < THUNK_SELECTOR = Thunk i'
203 | i == THUNK_SELECTOR = ThunkSelector
204 | i == BLACKHOLE = Blackhole
205 | i >= IND && i <= IND_STATIC = Indirection i'
206 | i' == aP_CODE = AP
207 | i == AP_STACK = AP
208 | i' == pAP_CODE = PAP
209 | i == MUT_VAR_CLEAN || i == MUT_VAR_DIRTY= MutVar i'
210 | i == MVAR_CLEAN || i == MVAR_DIRTY = MVar i'
211 | otherwise = Other i'
212 where i' = fromIntegral i
213
214 isConstr, isIndirection, isThunk :: ClosureType -> Bool
215 isConstr Constr = True
216 isConstr _ = False
217
218 isIndirection (Indirection _) = True
219 isIndirection _ = False
220
221 isThunk (Thunk _) = True
222 isThunk ThunkSelector = True
223 isThunk AP = True
224 isThunk _ = False
225
226 isFullyEvaluated :: DynFlags -> a -> IO Bool
227 isFullyEvaluated dflags a = do
228 closure <- getClosureData dflags a
229 case tipe closure of
230 Constr -> do are_subs_evaluated <- amapM (isFullyEvaluated dflags) (ptrs closure)
231 return$ and are_subs_evaluated
232 _ -> return False
233 where amapM f = sequence . amap' f
234
235 -- TODO: Fix it. Probably the otherwise case is failing, trace/debug it
236 {-
237 unsafeDeepSeq :: a -> b -> b
238 unsafeDeepSeq = unsafeDeepSeq1 2
239 where unsafeDeepSeq1 0 a b = seq a $! b
240 unsafeDeepSeq1 i a b -- 1st case avoids infinite loops for non reducible thunks
241 | not (isConstr tipe) = seq a $! unsafeDeepSeq1 (i-1) a b
242 -- | unsafePerformIO (isFullyEvaluated a) = b
243 | otherwise = case unsafePerformIO (getClosureData a) of
244 closure -> foldl' (flip unsafeDeepSeq) b (ptrs closure)
245 where tipe = unsafePerformIO (getClosureType a)
246 -}
247
248 -----------------------------------
249 -- * Traversals for Terms
250 -----------------------------------
251 type TermProcessor a b = RttiType -> Either String DataCon -> HValue -> [a] -> b
252
253 data TermFold a = TermFold { fTerm :: TermProcessor a a
254 , fPrim :: RttiType -> [Word] -> a
255 , fSuspension :: ClosureType -> RttiType -> HValue
256 -> Maybe Name -> a
257 , fNewtypeWrap :: RttiType -> Either String DataCon
258 -> a -> a
259 , fRefWrap :: RttiType -> a -> a
260 }
261
262
263 data TermFoldM m a =
264 TermFoldM {fTermM :: TermProcessor a (m a)
265 , fPrimM :: RttiType -> [Word] -> m a
266 , fSuspensionM :: ClosureType -> RttiType -> HValue
267 -> Maybe Name -> m a
268 , fNewtypeWrapM :: RttiType -> Either String DataCon
269 -> a -> m a
270 , fRefWrapM :: RttiType -> a -> m a
271 }
272
273 foldTerm :: TermFold a -> Term -> a
274 foldTerm tf (Term ty dc v tt) = fTerm tf ty dc v (map (foldTerm tf) tt)
275 foldTerm tf (Prim ty v ) = fPrim tf ty v
276 foldTerm tf (Suspension ct ty v b) = fSuspension tf ct ty v b
277 foldTerm tf (NewtypeWrap ty dc t) = fNewtypeWrap tf ty dc (foldTerm tf t)
278 foldTerm tf (RefWrap ty t) = fRefWrap tf ty (foldTerm tf t)
279
280
281 foldTermM :: Monad m => TermFoldM m a -> Term -> m a
282 foldTermM tf (Term ty dc v tt) = mapM (foldTermM tf) tt >>= fTermM tf ty dc v
283 foldTermM tf (Prim ty v ) = fPrimM tf ty v
284 foldTermM tf (Suspension ct ty v b) = fSuspensionM tf ct ty v b
285 foldTermM tf (NewtypeWrap ty dc t) = foldTermM tf t >>= fNewtypeWrapM tf ty dc
286 foldTermM tf (RefWrap ty t) = foldTermM tf t >>= fRefWrapM tf ty
287
288 idTermFold :: TermFold Term
289 idTermFold = TermFold {
290 fTerm = Term,
291 fPrim = Prim,
292 fSuspension = Suspension,
293 fNewtypeWrap = NewtypeWrap,
294 fRefWrap = RefWrap
295 }
296
297 mapTermType :: (RttiType -> Type) -> Term -> Term
298 mapTermType f = foldTerm idTermFold {
299 fTerm = \ty dc hval tt -> Term (f ty) dc hval tt,
300 fSuspension = \ct ty hval n ->
301 Suspension ct (f ty) hval n,
302 fNewtypeWrap= \ty dc t -> NewtypeWrap (f ty) dc t,
303 fRefWrap = \ty t -> RefWrap (f ty) t}
304
305 mapTermTypeM :: Monad m => (RttiType -> m Type) -> Term -> m Term
306 mapTermTypeM f = foldTermM TermFoldM {
307 fTermM = \ty dc hval tt -> f ty >>= \ty' -> return $ Term ty' dc hval tt,
308 fPrimM = (return.) . Prim,
309 fSuspensionM = \ct ty hval n ->
310 f ty >>= \ty' -> return $ Suspension ct ty' hval n,
311 fNewtypeWrapM= \ty dc t -> f ty >>= \ty' -> return $ NewtypeWrap ty' dc t,
312 fRefWrapM = \ty t -> f ty >>= \ty' -> return $ RefWrap ty' t}
313
314 termTyVars :: Term -> TyVarSet
315 termTyVars = foldTerm TermFold {
316 fTerm = \ty _ _ tt ->
317 tyVarsOfType ty `plusVarEnv` concatVarEnv tt,
318 fSuspension = \_ ty _ _ -> tyVarsOfType ty,
319 fPrim = \ _ _ -> emptyVarEnv,
320 fNewtypeWrap= \ty _ t -> tyVarsOfType ty `plusVarEnv` t,
321 fRefWrap = \ty t -> tyVarsOfType ty `plusVarEnv` t}
322 where concatVarEnv = foldr plusVarEnv emptyVarEnv
323
324 ----------------------------------
325 -- Pretty printing of terms
326 ----------------------------------
327
328 type Precedence = Int
329 type TermPrinter = Precedence -> Term -> SDoc
330 type TermPrinterM m = Precedence -> Term -> m SDoc
331
332 app_prec,cons_prec, max_prec ::Int
333 max_prec = 10
334 app_prec = max_prec
335 cons_prec = 5 -- TODO Extract this info from GHC itself
336
337 pprTerm :: TermPrinter -> TermPrinter
338 pprTerm y p t | Just doc <- pprTermM (\p -> Just . y p) p t = doc
339 pprTerm _ _ _ = panic "pprTerm"
340
341 pprTermM, ppr_termM, pprNewtypeWrap :: Monad m => TermPrinterM m -> TermPrinterM m
342 pprTermM y p t = pprDeeper `liftM` ppr_termM y p t
343
344 ppr_termM y p Term{dc=Left dc_tag, subTerms=tt} = do
345 tt_docs <- mapM (y app_prec) tt
346 return $ cparen (not (null tt) && p >= app_prec)
347 (text dc_tag <+> pprDeeperList fsep tt_docs)
348
349 ppr_termM y p Term{dc=Right dc, subTerms=tt}
350 {- | dataConIsInfix dc, (t1:t2:tt') <- tt --TODO fixity
351 = parens (ppr_term1 True t1 <+> ppr dc <+> ppr_term1 True ppr t2)
352 <+> hsep (map (ppr_term1 True) tt)
353 -} -- TODO Printing infix constructors properly
354 | null sub_terms_to_show
355 = return (ppr dc)
356 | otherwise
357 = do { tt_docs <- mapM (y app_prec) sub_terms_to_show
358 ; return $ cparen (p >= app_prec) $
359 sep [ppr dc, nest 2 (pprDeeperList fsep tt_docs)] }
360 where
361 sub_terms_to_show -- Don't show the dictionary arguments to
362 -- constructors unless -dppr-debug is on
363 | opt_PprStyle_Debug = tt
364 | otherwise = dropList (dataConTheta dc) tt
365
366 ppr_termM y p t@NewtypeWrap{} = pprNewtypeWrap y p t
367 ppr_termM y p RefWrap{wrapped_term=t} = do
368 contents <- y app_prec t
369 return$ cparen (p >= app_prec) (text "GHC.Prim.MutVar#" <+> contents)
370 -- The constructor name is wired in here ^^^ for the sake of simplicity.
371 -- I don't think mutvars are going to change in a near future.
372 -- In any case this is solely a presentation matter: MutVar# is
373 -- a datatype with no constructors, implemented by the RTS
374 -- (hence there is no way to obtain a datacon and print it).
375 ppr_termM _ _ t = ppr_termM1 t
376
377
378 ppr_termM1 :: Monad m => Term -> m SDoc
379 ppr_termM1 Prim{value=words, ty=ty} =
380 return $ repPrim (tyConAppTyCon ty) words
381 ppr_termM1 Suspension{ty=ty, bound_to=Nothing} =
382 return (char '_' <+> ifPprDebug (text "::" <> ppr ty))
383 ppr_termM1 Suspension{ty=ty, bound_to=Just n}
384 -- | Just _ <- splitFunTy_maybe ty = return$ ptext (sLit("<function>")
385 | otherwise = return$ parens$ ppr n <> text "::" <> ppr ty
386 ppr_termM1 Term{} = panic "ppr_termM1 - Term"
387 ppr_termM1 RefWrap{} = panic "ppr_termM1 - RefWrap"
388 ppr_termM1 NewtypeWrap{} = panic "ppr_termM1 - NewtypeWrap"
389
390 pprNewtypeWrap y p NewtypeWrap{ty=ty, wrapped_term=t}
391 | Just (tc,_) <- tcSplitTyConApp_maybe ty
392 , ASSERT(isNewTyCon tc) True
393 , Just new_dc <- tyConSingleDataCon_maybe tc = do
394 real_term <- y max_prec t
395 return $ cparen (p >= app_prec) (ppr new_dc <+> real_term)
396 pprNewtypeWrap _ _ _ = panic "pprNewtypeWrap"
397
398 -------------------------------------------------------
399 -- Custom Term Pretty Printers
400 -------------------------------------------------------
401
402 -- We can want to customize the representation of a
403 -- term depending on its type.
404 -- However, note that custom printers have to work with
405 -- type representations, instead of directly with types.
406 -- We cannot use type classes here, unless we employ some
407 -- typerep trickery (e.g. Weirich's RepLib tricks),
408 -- which I didn't. Therefore, this code replicates a lot
409 -- of what type classes provide for free.
410
411 type CustomTermPrinter m = TermPrinterM m
412 -> [Precedence -> Term -> (m (Maybe SDoc))]
413
414 -- | Takes a list of custom printers with a explicit recursion knot and a term,
415 -- and returns the output of the first successful printer, or the default printer
416 cPprTerm :: Monad m => CustomTermPrinter m -> Term -> m SDoc
417 cPprTerm printers_ = go 0 where
418 printers = printers_ go
419 go prec t = do
420 let default_ = Just `liftM` pprTermM go prec t
421 mb_customDocs = [pp prec t | pp <- printers] ++ [default_]
422 Just doc <- firstJustM mb_customDocs
423 return$ cparen (prec>app_prec+1) doc
424
425 firstJustM (mb:mbs) = mb >>= maybe (firstJustM mbs) (return . Just)
426 firstJustM [] = return Nothing
427
428 -- Default set of custom printers. Note that the recursion knot is explicit
429 cPprTermBase :: forall m. Monad m => CustomTermPrinter m
430 cPprTermBase y =
431 [ ifTerm (isTupleTy.ty) (\_p -> liftM (parens . hcat . punctuate comma)
432 . mapM (y (-1))
433 . subTerms)
434 , ifTerm (\t -> isTyCon listTyCon (ty t) && subTerms t `lengthIs` 2)
435 ppr_list
436 , ifTerm (isTyCon intTyCon . ty) ppr_int
437 , ifTerm (isTyCon charTyCon . ty) ppr_char
438 , ifTerm (isTyCon floatTyCon . ty) ppr_float
439 , ifTerm (isTyCon doubleTyCon . ty) ppr_double
440 , ifTerm (isIntegerTy . ty) ppr_integer
441 ]
442 where
443 ifTerm :: (Term -> Bool)
444 -> (Precedence -> Term -> m SDoc)
445 -> Precedence -> Term -> m (Maybe SDoc)
446 ifTerm pred f prec t@Term{}
447 | pred t = Just `liftM` f prec t
448 ifTerm _ _ _ _ = return Nothing
449
450 isTupleTy ty = fromMaybe False $ do
451 (tc,_) <- tcSplitTyConApp_maybe ty
452 return (isBoxedTupleTyCon tc)
453
454 isTyCon a_tc ty = fromMaybe False $ do
455 (tc,_) <- tcSplitTyConApp_maybe ty
456 return (a_tc == tc)
457
458 isIntegerTy ty = fromMaybe False $ do
459 (tc,_) <- tcSplitTyConApp_maybe ty
460 return (tyConName tc == integerTyConName)
461
462 ppr_int, ppr_char, ppr_float, ppr_double, ppr_integer
463 :: Precedence -> Term -> m SDoc
464 ppr_int _ v = return (Ppr.int (unsafeCoerce# (val v)))
465 ppr_char _ v = return (Ppr.char '\'' <> Ppr.char (unsafeCoerce# (val v)) <> Ppr.char '\'')
466 ppr_float _ v = return (Ppr.float (unsafeCoerce# (val v)))
467 ppr_double _ v = return (Ppr.double (unsafeCoerce# (val v)))
468 ppr_integer _ v = return (Ppr.integer (unsafeCoerce# (val v)))
469
470 --Note pprinting of list terms is not lazy
471 ppr_list :: Precedence -> Term -> m SDoc
472 ppr_list p (Term{subTerms=[h,t]}) = do
473 let elems = h : getListTerms t
474 isConsLast = not(termType(last elems) `eqType` termType h)
475 is_string = all (isCharTy . ty) elems
476
477 print_elems <- mapM (y cons_prec) elems
478 if is_string
479 then return (Ppr.doubleQuotes (Ppr.text (unsafeCoerce# (map val elems))))
480 else if isConsLast
481 then return $ cparen (p >= cons_prec)
482 $ pprDeeperList fsep
483 $ punctuate (space<>colon) print_elems
484 else return $ brackets
485 $ pprDeeperList fcat
486 $ punctuate comma print_elems
487
488 where getListTerms Term{subTerms=[h,t]} = h : getListTerms t
489 getListTerms Term{subTerms=[]} = []
490 getListTerms t@Suspension{} = [t]
491 getListTerms t = pprPanic "getListTerms" (ppr t)
492 ppr_list _ _ = panic "doList"
493
494
495 repPrim :: TyCon -> [Word] -> SDoc
496 repPrim t = rep where
497 rep x
498 | t == charPrimTyCon = text $ show (build x :: Char)
499 | t == intPrimTyCon = text $ show (build x :: Int)
500 | t == wordPrimTyCon = text $ show (build x :: Word)
501 | t == floatPrimTyCon = text $ show (build x :: Float)
502 | t == doublePrimTyCon = text $ show (build x :: Double)
503 | t == int32PrimTyCon = text $ show (build x :: Int32)
504 | t == word32PrimTyCon = text $ show (build x :: Word32)
505 | t == int64PrimTyCon = text $ show (build x :: Int64)
506 | t == word64PrimTyCon = text $ show (build x :: Word64)
507 | t == addrPrimTyCon = text $ show (nullPtr `plusPtr` build x)
508 | t == stablePtrPrimTyCon = text "<stablePtr>"
509 | t == stableNamePrimTyCon = text "<stableName>"
510 | t == statePrimTyCon = text "<statethread>"
511 | t == proxyPrimTyCon = text "<proxy>"
512 | t == realWorldTyCon = text "<realworld>"
513 | t == threadIdPrimTyCon = text "<ThreadId>"
514 | t == weakPrimTyCon = text "<Weak>"
515 | t == arrayPrimTyCon = text "<array>"
516 | t == byteArrayPrimTyCon = text "<bytearray>"
517 | t == mutableArrayPrimTyCon = text "<mutableArray>"
518 | t == mutableByteArrayPrimTyCon = text "<mutableByteArray>"
519 | t == mutVarPrimTyCon = text "<mutVar>"
520 | t == mVarPrimTyCon = text "<mVar>"
521 | t == tVarPrimTyCon = text "<tVar>"
522 | otherwise = char '<' <> ppr t <> char '>'
523 where build ww = unsafePerformIO $ withArray ww (peek . castPtr)
524 -- This ^^^ relies on the representation of Haskell heap values being
525 -- the same as in a C array.
526
527 -----------------------------------
528 -- Type Reconstruction
529 -----------------------------------
530 {-
531 Type Reconstruction is type inference done on heap closures.
532 The algorithm walks the heap generating a set of equations, which
533 are solved with syntactic unification.
534 A type reconstruction equation looks like:
535
536 <datacon reptype> = <actual heap contents>
537
538 The full equation set is generated by traversing all the subterms, starting
539 from a given term.
540
541 The only difficult part is that newtypes are only found in the lhs of equations.
542 Right hand sides are missing them. We can either (a) drop them from the lhs, or
543 (b) reconstruct them in the rhs when possible.
544
545 The function congruenceNewtypes takes a shot at (b)
546 -}
547
548
549 -- A (non-mutable) tau type containing
550 -- existentially quantified tyvars.
551 -- (since GHC type language currently does not support
552 -- existentials, we leave these variables unquantified)
553 type RttiType = Type
554
555 -- An incomplete type as stored in GHCi:
556 -- no polymorphism: no quantifiers & all tyvars are skolem.
557 type GhciType = Type
558
559
560 -- The Type Reconstruction monad
561 --------------------------------
562 type TR a = TcM a
563
564 runTR :: HscEnv -> TR a -> IO a
565 runTR hsc_env thing = do
566 mb_val <- runTR_maybe hsc_env thing
567 case mb_val of
568 Nothing -> error "unable to :print the term"
569 Just x -> return x
570
571 runTR_maybe :: HscEnv -> TR a -> IO (Maybe a)
572 runTR_maybe hsc_env thing_inside
573 = do { (_errs, res) <- initTc hsc_env HsSrcFile False
574 (icInteractiveModule (hsc_IC hsc_env))
575 thing_inside
576 ; return res }
577
578 traceTR :: SDoc -> TR ()
579 traceTR = liftTcM . traceOptTcRn Opt_D_dump_rtti
580
581
582 -- Semantically different to recoverM in TcRnMonad
583 -- recoverM retains the errors in the first action,
584 -- whereas recoverTc here does not
585 recoverTR :: TR a -> TR a -> TR a
586 recoverTR recover thing = do
587 (_,mb_res) <- tryTcErrs thing
588 case mb_res of
589 Nothing -> recover
590 Just res -> return res
591
592 trIO :: IO a -> TR a
593 trIO = liftTcM . liftIO
594
595 liftTcM :: TcM a -> TR a
596 liftTcM = id
597
598 newVar :: Kind -> TR TcType
599 newVar = liftTcM . newFlexiTyVarTy
600
601 instTyVars :: [TyVar] -> TR ([TcTyVar], [TcType], TvSubst)
602 -- Instantiate fresh mutable type variables from some TyVars
603 -- This function preserves the print-name, which helps error messages
604 instTyVars = liftTcM . tcInstTyVars
605
606 type RttiInstantiation = [(TcTyVar, TyVar)]
607 -- Associates the typechecker-world meta type variables
608 -- (which are mutable and may be refined), to their
609 -- debugger-world RuntimeUnk counterparts.
610 -- If the TcTyVar has not been refined by the runtime type
611 -- elaboration, then we want to turn it back into the
612 -- original RuntimeUnk
613
614 -- | Returns the instantiated type scheme ty', and the
615 -- mapping from new (instantiated) -to- old (skolem) type variables
616 instScheme :: QuantifiedType -> TR (TcType, RttiInstantiation)
617 instScheme (tvs, ty)
618 = liftTcM $ do { (tvs', _, subst) <- tcInstTyVars tvs
619 ; let rtti_inst = [(tv',tv) | (tv',tv) <- tvs' `zip` tvs]
620 ; return (substTy subst ty, rtti_inst) }
621
622 applyRevSubst :: RttiInstantiation -> TR ()
623 -- Apply the *reverse* substitution in-place to any un-filled-in
624 -- meta tyvars. This recovers the original debugger-world variable
625 -- unless it has been refined by new information from the heap
626 applyRevSubst pairs = liftTcM (mapM_ do_pair pairs)
627 where
628 do_pair (tc_tv, rtti_tv)
629 = do { tc_ty <- zonkTcTyVar tc_tv
630 ; case tcGetTyVar_maybe tc_ty of
631 Just tv | isMetaTyVar tv -> writeMetaTyVar tv (mkTyVarTy rtti_tv)
632 _ -> return () }
633
634 -- Adds a constraint of the form t1 == t2
635 -- t1 is expected to come from walking the heap
636 -- t2 is expected to come from a datacon signature
637 -- Before unification, congruenceNewtypes needs to
638 -- do its magic.
639 addConstraint :: TcType -> TcType -> TR ()
640 addConstraint actual expected = do
641 traceTR (text "add constraint:" <+> fsep [ppr actual, equals, ppr expected])
642 recoverTR (traceTR $ fsep [text "Failed to unify", ppr actual,
643 text "with", ppr expected]) $
644 do { (ty1, ty2) <- congruenceNewtypes actual expected
645 ; _ <- captureConstraints $ unifyType ty1 ty2
646 ; return () }
647 -- TOMDO: what about the coercion?
648 -- we should consider family instances
649
650
651 -- Type & Term reconstruction
652 ------------------------------
653 cvObtainTerm :: HscEnv -> Int -> Bool -> RttiType -> HValue -> IO Term
654 cvObtainTerm hsc_env max_depth force old_ty hval = runTR hsc_env $ do
655 -- we quantify existential tyvars as universal,
656 -- as this is needed to be able to manipulate
657 -- them properly
658 let quant_old_ty@(old_tvs, old_tau) = quantifyType old_ty
659 sigma_old_ty = mkForAllTys old_tvs old_tau
660 traceTR (text "Term reconstruction started with initial type " <> ppr old_ty)
661 term <-
662 if null old_tvs
663 then do
664 term <- go max_depth sigma_old_ty sigma_old_ty hval
665 term' <- zonkTerm term
666 return $ fixFunDictionaries $ expandNewtypes term'
667 else do
668 (old_ty', rev_subst) <- instScheme quant_old_ty
669 my_ty <- newVar openTypeKind
670 when (check1 quant_old_ty) (traceTR (text "check1 passed") >>
671 addConstraint my_ty old_ty')
672 term <- go max_depth my_ty sigma_old_ty hval
673 new_ty <- zonkTcType (termType term)
674 if isMonomorphic new_ty || check2 (quantifyType new_ty) quant_old_ty
675 then do
676 traceTR (text "check2 passed")
677 addConstraint new_ty old_ty'
678 applyRevSubst rev_subst
679 zterm' <- zonkTerm term
680 return ((fixFunDictionaries . expandNewtypes) zterm')
681 else do
682 traceTR (text "check2 failed" <+> parens
683 (ppr term <+> text "::" <+> ppr new_ty))
684 -- we have unsound types. Replace constructor types in
685 -- subterms with tyvars
686 zterm' <- mapTermTypeM
687 (\ty -> case tcSplitTyConApp_maybe ty of
688 Just (tc, _:_) | tc /= funTyCon
689 -> newVar openTypeKind
690 _ -> return ty)
691 term
692 zonkTerm zterm'
693 traceTR (text "Term reconstruction completed." $$
694 text "Term obtained: " <> ppr term $$
695 text "Type obtained: " <> ppr (termType term))
696 return term
697 where
698 dflags = hsc_dflags hsc_env
699
700 go :: Int -> Type -> Type -> HValue -> TcM Term
701 -- I believe that my_ty should not have any enclosing
702 -- foralls, nor any free RuntimeUnk skolems;
703 -- that is partly what the quantifyType stuff achieved
704 --
705 -- [SPJ May 11] I don't understand the difference between my_ty and old_ty
706
707 go max_depth _ _ _ | seq max_depth False = undefined
708 go 0 my_ty _old_ty a = do
709 traceTR (text "Gave up reconstructing a term after" <>
710 int max_depth <> text " steps")
711 clos <- trIO $ getClosureData dflags a
712 return (Suspension (tipe clos) my_ty a Nothing)
713 go max_depth my_ty old_ty a = do
714 let monomorphic = not(isTyVarTy my_ty)
715 -- This ^^^ is a convention. The ancestor tests for
716 -- monomorphism and passes a type instead of a tv
717 clos <- trIO $ getClosureData dflags a
718 case tipe clos of
719 -- Thunks we may want to force
720 t | isThunk t && force -> traceTR (text "Forcing a " <> text (show t)) >>
721 seq a (go (pred max_depth) my_ty old_ty a)
722 -- Blackholes are indirections iff the payload is not TSO or BLOCKING_QUEUE. So we
723 -- treat them like indirections; if the payload is TSO or BLOCKING_QUEUE, we'll end up
724 -- showing '_' which is what we want.
725 Blackhole -> do traceTR (text "Following a BLACKHOLE")
726 appArr (go max_depth my_ty old_ty) (ptrs clos) 0
727 -- We always follow indirections
728 Indirection i -> do traceTR (text "Following an indirection" <> parens (int i) )
729 go max_depth my_ty old_ty $! (ptrs clos ! 0)
730 -- We also follow references
731 MutVar _ | Just (tycon,[world,contents_ty]) <- tcSplitTyConApp_maybe old_ty
732 -> do
733 -- Deal with the MutVar# primitive
734 -- It does not have a constructor at all,
735 -- so we simulate the following one
736 -- MutVar# :: contents_ty -> MutVar# s contents_ty
737 traceTR (text "Following a MutVar")
738 contents_tv <- newVar liftedTypeKind
739 contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w
740 ASSERT(isUnliftedTypeKind $ typeKind my_ty) return ()
741 (mutvar_ty,_) <- instScheme $ quantifyType $ mkFunTy
742 contents_ty (mkTyConApp tycon [world,contents_ty])
743 addConstraint (mkFunTy contents_tv my_ty) mutvar_ty
744 x <- go (pred max_depth) contents_tv contents_ty contents
745 return (RefWrap my_ty x)
746
747 -- The interesting case
748 Constr -> do
749 traceTR (text "entering a constructor " <>
750 if monomorphic
751 then parens (text "already monomorphic: " <> ppr my_ty)
752 else Ppr.empty)
753 Right dcname <- dataConInfoPtrToName (infoPtr clos)
754 (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname)
755 case mb_dc of
756 Nothing -> do -- This can happen for private constructors compiled -O0
757 -- where the .hi descriptor does not export them
758 -- In such case, we return a best approximation:
759 -- ignore the unpointed args, and recover the pointeds
760 -- This preserves laziness, and should be safe.
761 traceTR (text "Not constructor" <+> ppr dcname)
762 let dflags = hsc_dflags hsc_env
763 tag = showPpr dflags dcname
764 vars <- replicateM (length$ elems$ ptrs clos)
765 (newVar liftedTypeKind)
766 subTerms <- sequence [appArr (go (pred max_depth) tv tv) (ptrs clos) i
767 | (i, tv) <- zip [0..] vars]
768 return (Term my_ty (Left ('<' : tag ++ ">")) a subTerms)
769 Just dc -> do
770 traceTR (text "Is constructor" <+> (ppr dc $$ ppr my_ty))
771 subTtypes <- getDataConArgTys dc my_ty
772 subTerms <- extractSubTerms (\ty -> go (pred max_depth) ty ty) clos subTtypes
773 return (Term my_ty (Right dc) a subTerms)
774
775 -- The otherwise case: can be a Thunk,AP,PAP,etc.
776 tipe_clos ->
777 return (Suspension tipe_clos my_ty a Nothing)
778
779 -- insert NewtypeWraps around newtypes
780 expandNewtypes = foldTerm idTermFold { fTerm = worker } where
781 worker ty dc hval tt
782 | Just (tc, args) <- tcSplitTyConApp_maybe ty
783 , isNewTyCon tc
784 , wrapped_type <- newTyConInstRhs tc args
785 , Just dc' <- tyConSingleDataCon_maybe tc
786 , t' <- worker wrapped_type dc hval tt
787 = NewtypeWrap ty (Right dc') t'
788 | otherwise = Term ty dc hval tt
789
790
791 -- Avoid returning types where predicates have been expanded to dictionaries.
792 fixFunDictionaries = foldTerm idTermFold {fSuspension = worker} where
793 worker ct ty hval n | isFunTy ty = Suspension ct (dictsView ty) hval n
794 | otherwise = Suspension ct ty hval n
795
796 extractSubTerms :: (Type -> HValue -> TcM Term)
797 -> Closure -> [Type] -> TcM [Term]
798 extractSubTerms recurse clos = liftM thirdOf3 . go 0 (nonPtrs clos)
799 where
800 go ptr_i ws [] = return (ptr_i, ws, [])
801 go ptr_i ws (ty:tys)
802 | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty
803 , isUnboxedTupleTyCon tc
804 = do (ptr_i, ws, terms0) <- go ptr_i ws elem_tys
805 (ptr_i, ws, terms1) <- go ptr_i ws tys
806 return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1)
807 | otherwise
808 = case repType ty of
809 UnaryRep rep_ty -> do
810 (ptr_i, ws, term0) <- go_rep ptr_i ws ty (typePrimRep rep_ty)
811 (ptr_i, ws, terms1) <- go ptr_i ws tys
812 return (ptr_i, ws, term0 : terms1)
813 UbxTupleRep rep_tys -> do
814 (ptr_i, ws, terms0) <- go_unary_types ptr_i ws rep_tys
815 (ptr_i, ws, terms1) <- go ptr_i ws tys
816 return (ptr_i, ws, unboxedTupleTerm ty terms0 : terms1)
817
818 go_unary_types ptr_i ws [] = return (ptr_i, ws, [])
819 go_unary_types ptr_i ws (rep_ty:rep_tys) = do
820 tv <- newVar liftedTypeKind
821 (ptr_i, ws, term0) <- go_rep ptr_i ws tv (typePrimRep rep_ty)
822 (ptr_i, ws, terms1) <- go_unary_types ptr_i ws rep_tys
823 return (ptr_i, ws, term0 : terms1)
824
825 go_rep ptr_i ws ty rep = case rep of
826 PtrRep -> do
827 t <- appArr (recurse ty) (ptrs clos) ptr_i
828 return (ptr_i + 1, ws, t)
829 _ -> do
830 dflags <- getDynFlags
831 let (ws0, ws1) = splitAt (primRepSizeW dflags rep) ws
832 return (ptr_i, ws1, Prim ty ws0)
833
834 unboxedTupleTerm ty terms = Term ty (Right (tupleCon UnboxedTuple (length terms)))
835 (error "unboxedTupleTerm: no HValue for unboxed tuple") terms
836
837
838 -- Fast, breadth-first Type reconstruction
839 ------------------------------------------
840 cvReconstructType :: HscEnv -> Int -> GhciType -> HValue -> IO (Maybe Type)
841 cvReconstructType hsc_env max_depth old_ty hval = runTR_maybe hsc_env $ do
842 traceTR (text "RTTI started with initial type " <> ppr old_ty)
843 let sigma_old_ty@(old_tvs, _) = quantifyType old_ty
844 new_ty <-
845 if null old_tvs
846 then return old_ty
847 else do
848 (old_ty', rev_subst) <- instScheme sigma_old_ty
849 my_ty <- newVar openTypeKind
850 when (check1 sigma_old_ty) (traceTR (text "check1 passed") >>
851 addConstraint my_ty old_ty')
852 search (isMonomorphic `fmap` zonkTcType my_ty)
853 (\(ty,a) -> go ty a)
854 (Seq.singleton (my_ty, hval))
855 max_depth
856 new_ty <- zonkTcType my_ty
857 if isMonomorphic new_ty || check2 (quantifyType new_ty) sigma_old_ty
858 then do
859 traceTR (text "check2 passed" <+> ppr old_ty $$ ppr new_ty)
860 addConstraint my_ty old_ty'
861 applyRevSubst rev_subst
862 zonkRttiType new_ty
863 else traceTR (text "check2 failed" <+> parens (ppr new_ty)) >>
864 return old_ty
865 traceTR (text "RTTI completed. Type obtained:" <+> ppr new_ty)
866 return new_ty
867 where
868 dflags = hsc_dflags hsc_env
869
870 -- search :: m Bool -> ([a] -> [a] -> [a]) -> [a] -> m ()
871 search _ _ _ 0 = traceTR (text "Failed to reconstruct a type after " <>
872 int max_depth <> text " steps")
873 search stop expand l d =
874 case viewl l of
875 EmptyL -> return ()
876 x :< xx -> unlessM stop $ do
877 new <- expand x
878 search stop expand (xx `mappend` Seq.fromList new) $! (pred d)
879
880 -- returns unification tasks,since we are going to want a breadth-first search
881 go :: Type -> HValue -> TR [(Type, HValue)]
882 go my_ty a = do
883 traceTR (text "go" <+> ppr my_ty)
884 clos <- trIO $ getClosureData dflags a
885 case tipe clos of
886 Blackhole -> appArr (go my_ty) (ptrs clos) 0 -- carefully, don't eval the TSO
887 Indirection _ -> go my_ty $! (ptrs clos ! 0)
888 MutVar _ -> do
889 contents <- trIO$ IO$ \w -> readMutVar# (unsafeCoerce# a) w
890 tv' <- newVar liftedTypeKind
891 world <- newVar liftedTypeKind
892 addConstraint my_ty (mkTyConApp mutVarPrimTyCon [world,tv'])
893 return [(tv', contents)]
894 Constr -> do
895 Right dcname <- dataConInfoPtrToName (infoPtr clos)
896 traceTR (text "Constr1" <+> ppr dcname)
897 (_,mb_dc) <- tryTcErrs (tcLookupDataCon dcname)
898 case mb_dc of
899 Nothing-> do
900 -- TODO: Check this case
901 forM [0..length (elems $ ptrs clos)] $ \i -> do
902 tv <- newVar liftedTypeKind
903 return$ appArr (\e->(tv,e)) (ptrs clos) i
904
905 Just dc -> do
906 arg_tys <- getDataConArgTys dc my_ty
907 (_, itys) <- findPtrTyss 0 arg_tys
908 traceTR (text "Constr2" <+> ppr dcname <+> ppr arg_tys)
909 return $ [ appArr (\e-> (ty,e)) (ptrs clos) i
910 | (i,ty) <- itys]
911 _ -> return []
912
913 findPtrTys :: Int -- Current pointer index
914 -> Type -- Type
915 -> TR (Int, [(Int, Type)])
916 findPtrTys i ty
917 | Just (tc, elem_tys) <- tcSplitTyConApp_maybe ty
918 , isUnboxedTupleTyCon tc
919 = findPtrTyss i elem_tys
920
921 | otherwise
922 = case repType ty of
923 UnaryRep rep_ty | typePrimRep rep_ty == PtrRep -> return (i + 1, [(i, ty)])
924 | otherwise -> return (i, [])
925 UbxTupleRep rep_tys -> foldM (\(i, extras) rep_ty -> if typePrimRep rep_ty == PtrRep
926 then newVar liftedTypeKind >>= \tv -> return (i + 1, extras ++ [(i, tv)])
927 else return (i, extras))
928 (i, []) rep_tys
929
930 findPtrTyss :: Int
931 -> [Type]
932 -> TR (Int, [(Int, Type)])
933 findPtrTyss i tys = foldM step (i, []) tys
934 where step (i, discovered) elem_ty = findPtrTys i elem_ty >>= \(i, extras) -> return (i, discovered ++ extras)
935
936
937 -- Compute the difference between a base type and the type found by RTTI
938 -- improveType <base_type> <rtti_type>
939 -- The types can contain skolem type variables, which need to be treated as normal vars.
940 -- In particular, we want them to unify with things.
941 improveRTTIType :: HscEnv -> RttiType -> RttiType -> Maybe TvSubst
942 improveRTTIType _ base_ty new_ty
943 = U.tcUnifyTys (const U.BindMe) [base_ty] [new_ty]
944
945 getDataConArgTys :: DataCon -> Type -> TR [Type]
946 -- Given the result type ty of a constructor application (D a b c :: ty)
947 -- return the types of the arguments. This is RTTI-land, so 'ty' might
948 -- not be fully known. Moreover, the arg types might involve existentials;
949 -- if so, make up fresh RTTI type variables for them
950 --
951 -- I believe that con_app_ty should not have any enclosing foralls
952 getDataConArgTys dc con_app_ty
953 = do { let UnaryRep rep_con_app_ty = repType con_app_ty
954 ; traceTR (text "getDataConArgTys 1" <+> (ppr con_app_ty $$ ppr rep_con_app_ty
955 $$ ppr (tcSplitTyConApp_maybe rep_con_app_ty)))
956 ; (_, _, subst) <- instTyVars (univ_tvs ++ ex_tvs)
957 ; addConstraint rep_con_app_ty (substTy subst (dataConOrigResTy dc))
958 -- See Note [Constructor arg types]
959 ; let con_arg_tys = substTys subst (dataConRepArgTys dc)
960 ; traceTR (text "getDataConArgTys 2" <+> (ppr rep_con_app_ty $$ ppr con_arg_tys $$ ppr subst))
961 ; return con_arg_tys }
962 where
963 univ_tvs = dataConUnivTyVars dc
964 ex_tvs = dataConExTyVars dc
965
966 {- Note [Constructor arg types]
967 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
968 Consider a GADT (cf Trac #7386)
969 data family D a b
970 data instance D [a] a where
971 MkT :: a -> D [a] (Maybe a)
972 ...
973
974 In getDataConArgTys
975 * con_app_ty is the known type (from outside) of the constructor application,
976 say D [Int] Int
977
978 * The data constructor MkT has a (representation) dataConTyCon = DList,
979 say where
980 data DList a where
981 MkT :: a -> DList a (Maybe a)
982 ...
983
984 So the dataConTyCon of the data constructor, DList, differs from
985 the "outside" type, D. So we can't straightforwardly decompose the
986 "outside" type, and we end up in the "_" branch of the case.
987
988 Then we match the dataConOrigResTy of the data constructor against the
989 outside type, hoping to get a substitution that tells how to instantiate
990 the *representation* type constructor. This looks a bit delicate to
991 me, but it seems to work.
992 -}
993
994 -- Soundness checks
995 --------------------
996 {-
997 This is not formalized anywhere, so hold to your seats!
998 RTTI in the presence of newtypes can be a tricky and unsound business.
999
1000 Example:
1001 ~~~~~~~~~
1002 Suppose we are doing RTTI for a partially evaluated
1003 closure t, the real type of which is t :: MkT Int, for
1004
1005 newtype MkT a = MkT [Maybe a]
1006
1007 The table below shows the results of RTTI and the improvement
1008 calculated for different combinations of evaluatedness and :type t.
1009 Regard the two first columns as input and the next two as output.
1010
1011 # | t | :type t | rtti(t) | improv. | result
1012 ------------------------------------------------------------
1013 1 | _ | t b | a | none | OK
1014 2 | _ | MkT b | a | none | OK
1015 3 | _ | t Int | a | none | OK
1016
1017 If t is not evaluated at *all*, we are safe.
1018
1019 4 | (_ : _) | t b | [a] | t = [] | UNSOUND
1020 5 | (_ : _) | MkT b | MkT a | none | OK (compensating for the missing newtype)
1021 6 | (_ : _) | t Int | [Int] | t = [] | UNSOUND
1022
1023 If a is a minimal whnf, we run into trouble. Note that
1024 row 5 above does newtype enrichment on the ty_rtty parameter.
1025
1026 7 | (Just _:_)| t b |[Maybe a] | t = [], | UNSOUND
1027 | | | b = Maybe a|
1028
1029 8 | (Just _:_)| MkT b | MkT a | none | OK
1030 9 | (Just _:_)| t Int | FAIL | none | OK
1031
1032 And if t is any more evaluated than whnf, we are still in trouble.
1033 Because constraints are solved in top-down order, when we reach the
1034 Maybe subterm what we got is already unsound. This explains why the
1035 row 9 fails to complete.
1036
1037 10 | (Just _:_)| t Int | [Maybe a] | FAIL | OK
1038 11 | (Just 1:_)| t Int | [Maybe Int] | FAIL | OK
1039
1040 We can undo the failure in row 9 by leaving out the constraint
1041 coming from the type signature of t (i.e., the 2nd column).
1042 Note that this type information is still used
1043 to calculate the improvement. But we fail
1044 when trying to calculate the improvement, as there is no unifier for
1045 t Int = [Maybe a] or t Int = [Maybe Int].
1046
1047
1048 Another set of examples with t :: [MkT (Maybe Int)] \equiv [[Maybe (Maybe Int)]]
1049
1050 # | t | :type t | rtti(t) | improvement | result
1051 ---------------------------------------------------------------------
1052 1 |(Just _:_) | [t (Maybe a)] | [[Maybe b]] | t = [] |
1053 | | | | b = Maybe a |
1054
1055 The checks:
1056 ~~~~~~~~~~~
1057 Consider a function obtainType that takes a value and a type and produces
1058 the Term representation and a substitution (the improvement).
1059 Assume an auxiliar rtti' function which does the actual job if recovering
1060 the type, but which may produce a false type.
1061
1062 In pseudocode:
1063
1064 rtti' :: a -> IO Type -- Does not use the static type information
1065
1066 obtainType :: a -> Type -> IO (Maybe (Term, Improvement))
1067 obtainType v old_ty = do
1068 rtti_ty <- rtti' v
1069 if monomorphic rtti_ty || (check rtti_ty old_ty)
1070 then ...
1071 else return Nothing
1072 where check rtti_ty old_ty = check1 rtti_ty &&
1073 check2 rtti_ty old_ty
1074
1075 check1 :: Type -> Bool
1076 check2 :: Type -> Type -> Bool
1077
1078 Now, if rtti' returns a monomorphic type, we are safe.
1079 If that is not the case, then we consider two conditions.
1080
1081
1082 1. To prevent the class of unsoundness displayed by
1083 rows 4 and 7 in the example: no higher kind tyvars
1084 accepted.
1085
1086 check1 (t a) = NO
1087 check1 (t Int) = NO
1088 check1 ([] a) = YES
1089
1090 2. To prevent the class of unsoundness shown by row 6,
1091 the rtti type should be structurally more
1092 defined than the old type we are comparing it to.
1093 check2 :: NewType -> OldType -> Bool
1094 check2 a _ = True
1095 check2 [a] a = True
1096 check2 [a] (t Int) = False
1097 check2 [a] (t a) = False -- By check1 we never reach this equation
1098 check2 [Int] a = True
1099 check2 [Int] (t Int) = True
1100 check2 [Maybe a] (t Int) = False
1101 check2 [Maybe Int] (t Int) = True
1102 check2 (Maybe [a]) (m [Int]) = False
1103 check2 (Maybe [Int]) (m [Int]) = True
1104
1105 -}
1106
1107 check1 :: QuantifiedType -> Bool
1108 check1 (tvs, _) = not $ any isHigherKind (map tyVarKind tvs)
1109 where
1110 isHigherKind = not . null . fst . splitKindFunTys
1111
1112 check2 :: QuantifiedType -> QuantifiedType -> Bool
1113 check2 (_, rtti_ty) (_, old_ty)
1114 | Just (_, rttis) <- tcSplitTyConApp_maybe rtti_ty
1115 = case () of
1116 _ | Just (_,olds) <- tcSplitTyConApp_maybe old_ty
1117 -> and$ zipWith check2 (map quantifyType rttis) (map quantifyType olds)
1118 _ | Just _ <- splitAppTy_maybe old_ty
1119 -> isMonomorphicOnNonPhantomArgs rtti_ty
1120 _ -> True
1121 | otherwise = True
1122
1123 -- Dealing with newtypes
1124 --------------------------
1125 {-
1126 congruenceNewtypes does a parallel fold over two Type values,
1127 compensating for missing newtypes on both sides.
1128 This is necessary because newtypes are not present
1129 in runtime, but sometimes there is evidence available.
1130 Evidence can come from DataCon signatures or
1131 from compile-time type inference.
1132 What we are doing here is an approximation
1133 of unification modulo a set of equations derived
1134 from newtype definitions. These equations should be the
1135 same as the equality coercions generated for newtypes
1136 in System Fc. The idea is to perform a sort of rewriting,
1137 taking those equations as rules, before launching unification.
1138
1139 The caller must ensure the following.
1140 The 1st type (lhs) comes from the heap structure of ptrs,nptrs.
1141 The 2nd type (rhs) comes from a DataCon type signature.
1142 Rewriting (i.e. adding/removing a newtype wrapper) can happen
1143 in both types, but in the rhs it is restricted to the result type.
1144
1145 Note that it is very tricky to make this 'rewriting'
1146 work with the unification implemented by TcM, where
1147 substitutions are operationally inlined. The order in which
1148 constraints are unified is vital as we cannot modify
1149 anything that has been touched by a previous unification step.
1150 Therefore, congruenceNewtypes is sound only if the types
1151 recovered by the RTTI mechanism are unified Top-Down.
1152 -}
1153 congruenceNewtypes :: TcType -> TcType -> TR (TcType,TcType)
1154 congruenceNewtypes lhs rhs = go lhs rhs >>= \rhs' -> return (lhs,rhs')
1155 where
1156 go l r
1157 -- TyVar lhs inductive case
1158 | Just tv <- getTyVar_maybe l
1159 , isTcTyVar tv
1160 , isMetaTyVar tv
1161 = recoverTR (return r) $ do
1162 Indirect ty_v <- readMetaTyVar tv
1163 traceTR $ fsep [text "(congruence) Following indirect tyvar:",
1164 ppr tv, equals, ppr ty_v]
1165 go ty_v r
1166 -- FunTy inductive case
1167 | Just (l1,l2) <- splitFunTy_maybe l
1168 , Just (r1,r2) <- splitFunTy_maybe r
1169 = do r2' <- go l2 r2
1170 r1' <- go l1 r1
1171 return (mkFunTy r1' r2')
1172 -- TyconApp Inductive case; this is the interesting bit.
1173 | Just (tycon_l, _) <- tcSplitTyConApp_maybe lhs
1174 , Just (tycon_r, _) <- tcSplitTyConApp_maybe rhs
1175 , tycon_l /= tycon_r
1176 = upgrade tycon_l r
1177
1178 | otherwise = return r
1179
1180 where upgrade :: TyCon -> Type -> TR Type
1181 upgrade new_tycon ty
1182 | not (isNewTyCon new_tycon) = do
1183 traceTR (text "(Upgrade) Not matching newtype evidence: " <>
1184 ppr new_tycon <> text " for " <> ppr ty)
1185 return ty
1186 | otherwise = do
1187 traceTR (text "(Upgrade) upgraded " <> ppr ty <>
1188 text " in presence of newtype evidence " <> ppr new_tycon)
1189 (_, vars, _) <- instTyVars (tyConTyVars new_tycon)
1190 let ty' = mkTyConApp new_tycon vars
1191 UnaryRep rep_ty = repType ty'
1192 _ <- liftTcM (unifyType ty rep_ty)
1193 -- assumes that reptype doesn't ^^^^ touch tyconApp args
1194 return ty'
1195
1196
1197 zonkTerm :: Term -> TcM Term
1198 zonkTerm = foldTermM (TermFoldM
1199 { fTermM = \ty dc v tt -> zonkRttiType ty >>= \ty' ->
1200 return (Term ty' dc v tt)
1201 , fSuspensionM = \ct ty v b -> zonkRttiType ty >>= \ty ->
1202 return (Suspension ct ty v b)
1203 , fNewtypeWrapM = \ty dc t -> zonkRttiType ty >>= \ty' ->
1204 return$ NewtypeWrap ty' dc t
1205 , fRefWrapM = \ty t -> return RefWrap `ap`
1206 zonkRttiType ty `ap` return t
1207 , fPrimM = (return.) . Prim })
1208
1209 zonkRttiType :: TcType -> TcM Type
1210 -- Zonk the type, replacing any unbound Meta tyvars
1211 -- by skolems, safely out of Meta-tyvar-land
1212 zonkRttiType = zonkTcTypeToType (mkEmptyZonkEnv zonk_unbound_meta)
1213 where
1214 zonk_unbound_meta tv
1215 = ASSERT( isTcTyVar tv )
1216 do { tv' <- skolemiseUnboundMetaTyVar tv RuntimeUnk
1217 -- This is where RuntimeUnks are born:
1218 -- otherwise-unconstrained unification variables are
1219 -- turned into RuntimeUnks as they leave the
1220 -- typechecker's monad
1221 ; return (mkTyVarTy tv') }
1222
1223 --------------------------------------------------------------------------------
1224 -- Restore Class predicates out of a representation type
1225 dictsView :: Type -> Type
1226 dictsView ty = ty
1227
1228
1229 -- Use only for RTTI types
1230 isMonomorphic :: RttiType -> Bool
1231 isMonomorphic ty = noExistentials && noUniversals
1232 where (tvs, _, ty') = tcSplitSigmaTy ty
1233 noExistentials = isEmptyVarSet (tyVarsOfType ty')
1234 noUniversals = null tvs
1235
1236 -- Use only for RTTI types
1237 isMonomorphicOnNonPhantomArgs :: RttiType -> Bool
1238 isMonomorphicOnNonPhantomArgs ty
1239 | UnaryRep rep_ty <- repType ty
1240 , Just (tc, all_args) <- tcSplitTyConApp_maybe rep_ty
1241 , phantom_vars <- tyConPhantomTyVars tc
1242 , concrete_args <- [ arg | (tyv,arg) <- tyConTyVars tc `zip` all_args
1243 , tyv `notElem` phantom_vars]
1244 = all isMonomorphicOnNonPhantomArgs concrete_args
1245 | Just (ty1, ty2) <- splitFunTy_maybe ty
1246 = all isMonomorphicOnNonPhantomArgs [ty1,ty2]
1247 | otherwise = isMonomorphic ty
1248
1249 tyConPhantomTyVars :: TyCon -> [TyVar]
1250 tyConPhantomTyVars tc
1251 | isAlgTyCon tc
1252 , Just dcs <- tyConDataCons_maybe tc
1253 , dc_vars <- concatMap dataConUnivTyVars dcs
1254 = tyConTyVars tc \\ dc_vars
1255 tyConPhantomTyVars _ = []
1256
1257 type QuantifiedType = ([TyVar], Type)
1258 -- Make the free type variables explicit
1259 -- The returned Type should have no top-level foralls (I believe)
1260
1261 quantifyType :: Type -> QuantifiedType
1262 -- Generalize the type: find all free and forall'd tyvars
1263 -- and return them, together with the type inside, which
1264 -- should not be a forall type.
1265 --
1266 -- Thus (quantifyType (forall a. a->[b]))
1267 -- returns ([a,b], a -> [b])
1268
1269 quantifyType ty = (varSetElems (tyVarsOfType rho), rho)
1270 where
1271 (_tvs, rho) = tcSplitForAllTys ty
1272
1273 unlessM :: Monad m => m Bool -> m () -> m ()
1274 unlessM condM acc = condM >>= \c -> unless c acc
1275
1276
1277 -- Strict application of f at index i
1278 appArr :: Ix i => (e -> a) -> Array i e -> Int -> a
1279 appArr f a@(Array _ _ _ ptrs#) i@(I# i#)
1280 = ASSERT2(i < length(elems a), ppr(length$ elems a, i))
1281 case indexArray# ptrs# i# of
1282 (# e #) -> f e
1283
1284 amap' :: (t -> b) -> Array Int t -> [b]
1285 amap' f (Array i0 i _ arr#) = map g [0 .. i - i0]
1286 where g (I# i#) = case indexArray# arr# i# of
1287 (# e #) -> f e