Type.lhs 42.9 KB
Newer Older
1
2
3
%
% (c) The GRASP/AQUA Project, Glasgow University, 1998
%
4
\section[Type]{Type - public interface}
5

6
7
\begin{code}
module Type (
8
        -- re-exports from TypeRep
9
	TyThing(..), Type, PredType(..), ThetaType, 
10
	funTyCon,
11

12
13
14
	-- Re-exports from Kind
	module Kind,

15
16
	-- Re-exports from TyCon
	PrimRep(..),
17

18
19
	mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,

20
	mkAppTy, mkAppTys, splitAppTy, splitAppTys, splitAppTy_maybe,
21

22
23
	mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, 
	splitFunTys, splitFunTysN,
24
	funResultTy, funArgTy, zipFunTys, isFunTy,
25

26
	mkGenTyConApp, mkTyConApp, mkTyConTy, 
27
28
	tyConAppTyCon, tyConAppArgs, 
	splitTyConApp_maybe, splitTyConApp,
29

30
	mkSynTy, 
31

32
	repType, typePrimRep, coreView, tcView,
33

34
	mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, 
35
	applyTy, applyTys, isForAllTy, dropForAlls,
36

37
	-- Source types
38
	predTypeRep, mkPredTy, mkPredTys,
39

40
	-- Newtypes
41
	splitRecNewType_maybe,
42

43
	-- Lifting and boxity
44
45
	isUnLiftedType, isUnboxedTupleType, isAlgType, isPrimitiveType,
	isStrictType, isStrictPred, 
46

47
	-- Free variables
48
	tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
49
	typeKind, addFreeTyVars,
50

51
	-- Tidying up for printing
52
53
54
55
56
	tidyType,      tidyTypes,
	tidyOpenType,  tidyOpenTypes,
	tidyTyVarBndr, tidyFreeTyVars,
	tidyOpenTyVar, tidyOpenTyVars,
	tidyTopType,   tidyPred,
57
	tidyKind,
58

59
	-- Comparison
60
61
	coreEqType, tcEqType, tcEqTypes, tcCmpType, tcCmpTypes, 
	tcEqPred, tcCmpPred, tcEqTypeX, 
62

63
	-- Seq
64
	seqType, seqTypes,
65

66
	-- Type substitutions
67
68
	TvSubstEnv, emptyTvSubstEnv,	-- Representation widely visible
	TvSubst(..), emptyTvSubst,	-- Representation visible to a few friends
69
	mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
70
	getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope,
71
 	extendTvSubst, extendTvSubstList, isInScope, composeTvSubst,
72
73

	-- Performing substitution on types
74
75
	substTy, substTys, substTyWith, substTheta, 
	substPred, substTyVar, substTyVarBndr, deShadowTy, 
76

77
	-- Pretty-printing
78
	pprType, pprParendType, pprTyThingCategory,
79
	pprPred, pprTheta, pprThetaArrow, pprClassPred
80
    ) where
81

82
83
#include "HsVersions.h"

84
85
86
87
88
-- We import the representation and primitive functions from TypeRep.
-- Many things are reexported, but not the representation!

import TypeRep

89
-- friends:
90
import Kind
91
import Var	( Var, TyVar, tyVarKind, tyVarName, setTyVarName, mkTyVar )
92
93
94
import VarEnv
import VarSet

95
import Name	( NamedThing(..), mkInternalName, tidyOccName )
96
import Class	( Class, classTyCon )
97
import TyCon	( TyCon, isRecursiveTyCon, isPrimTyCon,
98
		  isUnboxedTupleTyCon, isUnLiftedTyCon,
99
		  isFunTyCon, isNewTyCon, newTyConRep, newTyConRhs,
100
101
102
		  isAlgTyCon, tyConArity, 
		  tcExpandTyCon_maybe, coreExpandTyCon_maybe,
	          tyConKind, PrimRep(..), tyConPrimRep,
103
104
		)

105
-- others
106
import StaticFlags	( opt_DictsStrict )
107
108
import SrcLoc		( noSrcLoc )
import Unique		( Uniquable(..) )
109
import Util		( mapAccumL, seqList, lengthIs, snocView, thenCmp, isEqual, all2 )
110
import Outputable
111
import UniqSet		( sizeUniqSet )		-- Should come via VarSet
112
import Maybe		( isJust )
113
114
\end{code}

115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
%************************************************************************
%*									*
		Type representation
%*									*
%************************************************************************

In Core, we "look through" non-recursive newtypes and PredTypes.

\begin{code}
{-# INLINE coreView #-}
coreView :: Type -> Maybe Type
-- Srips off the *top layer only* of a type to give 
-- its underlying representation type. 
-- Returns Nothing if there is nothing to look through.
--
131
-- In the case of newtypes, it returns
132
133
134
135
136
137
138
139
140
141
142
143
--	*either* a vanilla TyConApp (recursive newtype, or non-saturated)
--	*or*     the newtype representation (otherwise), meaning the
--			type written in the RHS of the newtype decl,
--			which may itself be a newtype
--
-- Example: newtype R = MkR S
--	    newtype S = MkS T
--	    newtype T = MkT (T -> T)
--   expandNewTcApp on R gives Just S
--	            on S gives Just T
--		    on T gives Nothing	 (no expansion)

144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
-- By being non-recursive and inlined, this case analysis gets efficiently
-- joined onto the case analysis that the caller is already doing
coreView (NoteTy _ ty) 	   = Just ty
coreView (PredTy p)    	   = Just (predTypeRep p)
coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys 
			   = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
				-- Its important to use mkAppTys, rather than (foldl AppTy),
				-- because the function part might well return a 
				-- partially-applied type constructor; indeed, usually will!
coreView ty		   = Nothing

-----------------------------------------------
{-# INLINE tcView #-}
tcView :: Type -> Maybe Type
-- Same, but for the type checker, which just looks through synonyms
tcView (NoteTy _ ty) 	 = Just ty
tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys 
			 = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
tcView ty		 = Nothing
163
164
165
\end{code}


166
167
168
169
170
%************************************************************************
%*									*
\subsection{Constructor-specific functions}
%*									*
%************************************************************************
sof's avatar
sof committed
171
172


173
174
175
---------------------------------------------------------------------
				TyVarTy
				~~~~~~~
176
\begin{code}
177
mkTyVarTy  :: TyVar   -> Type
178
mkTyVarTy  = TyVarTy
179

180
mkTyVarTys :: [TyVar] -> [Type]
181
mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
182

183
getTyVar :: String -> Type -> TyVar
184
185
186
getTyVar msg ty = case getTyVar_maybe ty of
		    Just tv -> tv
		    Nothing -> panic ("getTyVar: " ++ msg)
187

188
isTyVarTy :: Type -> Bool
189
190
191
isTyVarTy ty = isJust (getTyVar_maybe ty)

getTyVar_maybe :: Type -> Maybe TyVar
192
193
194
getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
getTyVar_maybe (TyVarTy tv) 	 	    = Just tv  
getTyVar_maybe other	         	    = Nothing
195
196
197
\end{code}


198
199
200
201
202
203
---------------------------------------------------------------------
				AppTy
				~~~~~
We need to be pretty careful with AppTy to make sure we obey the 
invariant that a TyConApp is always visibly so.  mkAppTy maintains the
invariant: use it.
204

205
\begin{code}
206
mkAppTy orig_ty1 orig_ty2
207
  = mk_app orig_ty1
208
  where
209
    mk_app (NoteTy _ ty1)    = mk_app ty1
210
    mk_app (TyConApp tc tys) = mkGenTyConApp tc (tys ++ [orig_ty2])
211
    mk_app ty1		     = AppTy orig_ty1 orig_ty2
212
213
214
215
216
217
218
219
	-- We call mkGenTyConApp because the TyConApp could be an 
	-- under-saturated type synonym.  GHC allows that; e.g.
	--	type Foo k = k a -> k a
	--	type Id x = x
	--	foo :: Foo Id -> Foo Id
	--
	-- Here Id is partially applied in the type sig for Foo,
	-- but once the type synonyms are expanded all is well
220

221
mkAppTys :: Type -> [Type] -> Type
222
223
mkAppTys orig_ty1 []	    = orig_ty1
	-- This check for an empty list of type arguments
224
	-- avoids the needless loss of a type synonym constructor.
225
226
227
	-- For example: mkAppTys Rational []
	--   returns to (Ratio Integer), which has needlessly lost
	--   the Rational part.
228
mkAppTys orig_ty1 orig_tys2
229
  = mk_app orig_ty1
230
  where
231
    mk_app (NoteTy _ ty1)    = mk_app ty1
232
233
    mk_app (TyConApp tc tys) = mkGenTyConApp tc (tys ++ orig_tys2)
				-- mkGenTyConApp: see notes with mkAppTy
234
    mk_app ty1		     = foldl AppTy orig_ty1 orig_tys2
235

236
splitAppTy_maybe :: Type -> Maybe (Type, Type)
237
splitAppTy_maybe ty | Just ty' <- coreView ty = splitAppTy_maybe ty'
238
splitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
239
splitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
240
splitAppTy_maybe (TyConApp tc tys) = case snocView tys of
241
242
					Nothing         -> Nothing
					Just (tys',ty') -> Just (TyConApp tc tys', ty')
243
splitAppTy_maybe other	     	   = Nothing
244

245
splitAppTy :: Type -> (Type, Type)
246
247
248
splitAppTy ty = case splitAppTy_maybe ty of
			Just pr -> pr
			Nothing -> panic "splitAppTy"
249

250
splitAppTys :: Type -> (Type, [Type])
251
splitAppTys ty = split ty ty []
252
  where
253
    split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
254
    split orig_ty (AppTy ty arg)        args = split ty ty (arg:args)
255
    split orig_ty (TyConApp tc tc_args) args = (TyConApp tc [], tc_args ++ args)
256
    split orig_ty (FunTy ty1 ty2)       args = ASSERT( null args )
257
					       (TyConApp funTyCon [], [ty1,ty2])
258
    split orig_ty ty		        args = (orig_ty, args)
259
260
\end{code}

261
262
263
264
265

---------------------------------------------------------------------
				FunTy
				~~~~~

266
\begin{code}
267
mkFunTy :: Type -> Type -> Type
268
mkFunTy arg res = FunTy arg res
269

270
mkFunTys :: [Type] -> Type -> Type
271
mkFunTys tys ty = foldr FunTy ty tys
272

273
274
275
isFunTy :: Type -> Bool 
isFunTy ty = isJust (splitFunTy_maybe ty)

276
splitFunTy :: Type -> (Type, Type)
277
splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
278
splitFunTy (FunTy arg res)   = (arg, res)
279
splitFunTy other	     = pprPanic "splitFunTy" (ppr other)
280

281
splitFunTy_maybe :: Type -> Maybe (Type, Type)
282
splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
283
284
splitFunTy_maybe (FunTy arg res)   = Just (arg, res)
splitFunTy_maybe other	           = Nothing
285

286
splitFunTys :: Type -> ([Type], Type)
287
splitFunTys ty = split [] ty ty
288
  where
289
    split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
290
291
    split args orig_ty (FunTy arg res) 	 = split (arg:args) res res
    split args orig_ty ty                = (reverse args, orig_ty)
292

293
294
295
296
297
298
299
splitFunTysN :: Int -> Type -> ([Type], Type)
-- Split off exactly n arg tys
splitFunTysN 0 ty = ([], ty)
splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
		    case splitFunTysN (n-1) res of { (args, res) ->
		    (arg:args, res) }}

300
301
302
zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
  where
303
    split acc []     nty ty  	           = (reverse acc, nty)
304
305
    split acc xs     nty ty 
	  | Just ty' <- coreView ty 	   = split acc xs nty ty'
306
    split acc (x:xs) nty (FunTy arg res)   = split ((x,arg):acc) xs res res
307
    split acc (x:xs) nty ty                = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
308
309
    
funResultTy :: Type -> Type
310
funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
311
funResultTy (FunTy arg res)   = res
312
funResultTy ty		      = pprPanic "funResultTy" (ppr ty)
313
314

funArgTy :: Type -> Type
315
funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
316
funArgTy (FunTy arg res)   = arg
317
funArgTy ty		   = pprPanic "funArgTy" (ppr ty)
318
319
320
\end{code}


321
322
323
---------------------------------------------------------------------
				TyConApp
				~~~~~~~~
324
@mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or PredTy,
325
as apppropriate.
326

327
\begin{code}
328
329
mkGenTyConApp :: TyCon -> [Type] -> Type
mkGenTyConApp tc tys
330
  = mkTyConApp tc tys
331

332
mkTyConApp :: TyCon -> [Type] -> Type
333
mkTyConApp tycon tys
334
  | isFunTyCon tycon, [ty1,ty2] <- tys
335
  = FunTy ty1 ty2
336

337
  | otherwise
338
  = TyConApp tycon tys
339

340
mkTyConTy :: TyCon -> Type
341
mkTyConTy tycon = mkTyConApp tycon []
342
343
344
345
346

-- splitTyConApp "looks through" synonyms, because they don't
-- mean a distinct type, but all other type-constructor applications
-- including functions are returned as Just ..

347
tyConAppTyCon :: Type -> TyCon
348
tyConAppTyCon ty = fst (splitTyConApp ty)
349
350

tyConAppArgs :: Type -> [Type]
351
tyConAppArgs ty = snd (splitTyConApp ty)
352
353
354
355

splitTyConApp :: Type -> (TyCon, [Type])
splitTyConApp ty = case splitTyConApp_maybe ty of
			Just stuff -> stuff
356
			Nothing	   -> pprPanic "splitTyConApp" (ppr ty)
357

358
splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
359
splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
360
splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
361
splitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
362
splitTyConApp_maybe other	      = Nothing
sof's avatar
sof committed
363
\end{code}
364

365

366
367
368
369
---------------------------------------------------------------------
				SynTy
				~~~~~

370
\begin{code}
371
372
mkSynTy tycon tys = panic "No longer used"
{-	Delete in due course
373
374
375
  | n_args == arity	-- Exactly saturated
  = mk_syn tys
  | n_args >  arity	-- Over-saturated
376
377
378
379
  = case splitAt arity tys of { (as,bs) -> mkAppTys (mk_syn as) bs }
	-- Its important to use mkAppTys, rather than (foldl AppTy),
	-- because (mk_syn as) might well return a partially-applied
	-- type constructor; indeed, usually will!
380
381
382
383
384
385
386
387
  | otherwise		-- Un-saturated
  = TyConApp tycon tys
	-- For the un-saturated case we build TyConApp directly
	-- (mkTyConApp ASSERTs that the tc isn't a SynTyCon).
	-- Here we are relying on checkValidType to find
	-- the error.  What we can't do is use mkSynTy with
	-- too few arg tys, because that is utterly bogus.

388
  where
389
390
391
392
393
394
    mk_syn tys = NoteTy (SynNote (TyConApp tycon tys))
			(substTyWith tyvars tys body)

    (tyvars, body) = ASSERT( isSynTyCon tycon ) getSynTyConDefn tycon
    arity 	   = tyConArity tycon
    n_args	   = length tys
395
-}
396
397
\end{code}

398
399
400
401
Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
to return type synonyms whereever possible. Thus
402

403
404
405
406
407
408
409
410
	type Foo a = a -> a

we want 
	splitFunTys (a -> Foo a) = ([a], Foo a)
not			           ([a], a -> a)

The reason is that we then get better (shorter) type signatures in 
interfaces.  Notably this plays a role in tcTySigs in TcBinds.lhs.
411
412


413
414
		Representation types
		~~~~~~~~~~~~~~~~~~~~
415
416
repType looks through 
	(a) for-alls, and
417
418
419
	(b) synonyms
	(c) predicates
	(d) usage annotations
420
	(e) all newtypes, including recursive ones
421
It's useful in the back end.
422
423
424

\begin{code}
repType :: Type -> Type
425
-- Only applied to types of kind *; hence tycons are saturated
426
427
428
429
repType (ForAllTy _ ty)   	     = repType ty
repType (NoteTy   _ ty)   	     = repType ty
repType ty | Just ty' <- coreView ty = repType ty'
  	   | otherwise		     = ty
430

431
432
-- ToDo: this could be moved to the code generator, using splitTyConApp instead
-- of inspecting the type directly.
433
434
435
436
typePrimRep :: Type -> PrimRep
typePrimRep ty = case repType ty of
		   TyConApp tc _ -> tyConPrimRep tc
		   FunTy _ _	 -> PtrRep
437
		   AppTy _ _	 -> PtrRep	-- See note below
438
		   TyVarTy _	 -> PtrRep
439
		   other	 -> pprPanic "typePrimRep" (ppr ty)
440
441
442
443
444
	-- Types of the form 'f a' must be of kind *, not *#, so
	-- we are guaranteed that they are represented by pointers.
	-- The reason is that f must have kind *->*, not *->*#, because
	-- (we claim) there is no way to constrain f's kind any other
	-- way.
445
446
447
448
449
450

-- new_type_rep doesn't ask any questions: 
-- it just expands newtype, whether recursive or not
new_type_rep new_tycon tys = ASSERT( tys `lengthIs` tyConArity new_tycon )
			     case newTyConRep new_tycon of
				 (tvs, rep_ty) -> substTyWith tvs tys rep_ty
451
452
453
\end{code}


454
455
456
---------------------------------------------------------------------
				ForAllTy
				~~~~~~~~
457
458

\begin{code}
459
mkForAllTy :: TyVar -> Type -> Type
460
461
mkForAllTy tyvar ty
  = mkForAllTys [tyvar] ty
462

463
mkForAllTys :: [TyVar] -> Type -> Type
464
mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
465
466
467
468
469

isForAllTy :: Type -> Bool
isForAllTy (NoteTy _ ty)  = isForAllTy ty
isForAllTy (ForAllTy _ _) = True
isForAllTy other_ty	  = False
470

471
splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
472
splitForAllTy_maybe ty = splitFAT_m ty
473
  where
474
475
476
    splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
    splitFAT_m (ForAllTy tyvar ty)	    = Just(tyvar, ty)
    splitFAT_m _			    = Nothing
sof's avatar
sof committed
477

478
splitForAllTys :: Type -> ([TyVar], Type)
479
splitForAllTys ty = split ty ty []
480
   where
481
     split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
482
483
     split orig_ty (ForAllTy tv ty)  tvs = split ty ty (tv:tvs)
     split orig_ty t		     tvs = (reverse tvs, orig_ty)
484
485
486

dropForAlls :: Type -> Type
dropForAlls ty = snd (splitForAllTys ty)
487
488
\end{code}

489
-- (mkPiType now in CoreUtils)
490

491
492
493
494
495
496
497
applyTy, applyTys
~~~~~~~~~~~~~~~~~
Instantiate a for-all type with one or more type arguments.
Used when we have a polymorphic function applied to type args:
	f t1 t2
Then we use (applyTys type-of-f [t1,t2]) to compute the type of
the expression. 
498

499
\begin{code}
500
applyTy :: Type -> Type -> Type
501
502
503
applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
applyTy other		 arg = panic "applyTy"
504

505
applyTys :: Type -> [Type] -> Type
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
-- This function is interesting because 
--	a) the function may have more for-alls than there are args
--	b) less obviously, it may have fewer for-alls
-- For case (b) think of 
--	applyTys (forall a.a) [forall b.b, Int]
-- This really can happen, via dressing up polymorphic types with newtype
-- clothing.  Here's an example:
--	newtype R = R (forall a. a->a)
--	foo = case undefined :: R of
--		R f -> f ()

applyTys orig_fun_ty []      = orig_fun_ty
applyTys orig_fun_ty arg_tys 
  | n_tvs == n_args 	-- The vastly common case
  = substTyWith tvs arg_tys rho_ty
  | n_tvs > n_args 	-- Too many for-alls
  = substTyWith (take n_args tvs) arg_tys 
		(mkForAllTys (drop n_args tvs) rho_ty)
  | otherwise		-- Too many type args
525
  = ASSERT2( n_tvs > 0, ppr orig_fun_ty )	-- Zero case gives infnite loop!
526
527
528
529
530
531
    applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
	     (drop n_tvs arg_tys)
  where
    (tvs, rho_ty) = splitForAllTys orig_fun_ty 
    n_tvs = length tvs
    n_args = length arg_tys     
532
\end{code}
533

534

535
536
%************************************************************************
%*									*
537
\subsection{Source types}
538
539
%*									*
%************************************************************************
540

541
542
A "source type" is a type that is a separate type as far as the type checker is
concerned, but which has low-level representation as far as the back end is concerned.
543

544
Source types are always lifted.
545

546
The key function is predTypeRep which gives the representation of a source type:
547
548

\begin{code}
549
mkPredTy :: PredType -> Type
550
mkPredTy pred = PredTy pred
551
552

mkPredTys :: ThetaType -> [Type]
553
554
555
556
557
mkPredTys preds = map PredTy preds

predTypeRep :: PredType -> Type
-- Convert a PredType to its "representation type";
-- the post-type-checking type used by all the Core passes of GHC.
558
-- Unwraps only the outermost level; for example, the result might
559
-- be a newtype application
560
561
predTypeRep (IParam _ ty)     = ty
predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
562
	-- Result might be a newtype application, but the consumer will
563
564
	-- look through that too if necessary
\end{code}
565
566


567
568
569
570
571
%************************************************************************
%*									*
		NewTypes
%*									*
%************************************************************************
572

573
574
575
\begin{code}
splitRecNewType_maybe :: Type -> Maybe Type
-- Sometimes we want to look through a recursive newtype, and that's what happens here
576
-- It only strips *one layer* off, so the caller will usually call itself recursively
577
-- Only applied to types of kind *, hence the newtype is always saturated
578
579
580
581
582
583
584
splitRecNewType_maybe ty | Just ty' <- coreView ty = splitRecNewType_maybe ty'
splitRecNewType_maybe (TyConApp tc tys)
  | isNewTyCon tc
  = ASSERT( tys `lengthIs` tyConArity tc )	-- splitRecNewType_maybe only be applied 
						-- 	to *types* (of kind *)
    ASSERT( isRecursiveTyCon tc ) 		-- Guaranteed by coreView
    case newTyConRhs tc of
585
586
587
	(tvs, rep_ty) -> ASSERT( length tvs == length tys )
			 Just (substTyWith tvs tys rep_ty)
	
588
splitRecNewType_maybe other = Nothing
589
590
\end{code}

591

592
593
594
595
596
597
598
599
600
%************************************************************************
%*									*
\subsection{Kinds and free variables}
%*									*
%************************************************************************

---------------------------------------------------------------------
		Finding the kind of a type
		~~~~~~~~~~~~~~~~~~~~~~~~~~
601
\begin{code}
602
typeKind :: Type -> Kind
603

604
typeKind (TyVarTy tyvar)	= tyVarKind tyvar
605
typeKind (TyConApp tycon tys)	= foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
606
typeKind (NoteTy _ ty)		= typeKind ty
607
typeKind (PredTy _)		= liftedTypeKind -- Predicates are always 
608
						 -- represented by lifted types
609
610
typeKind (AppTy fun arg)	= kindFunResult (typeKind fun)
typeKind (FunTy arg res)	= liftedTypeKind
611
typeKind (ForAllTy tv ty)	= typeKind ty
612
613
614
\end{code}


615
616
617
---------------------------------------------------------------------
		Free variables of a type
		~~~~~~~~~~~~~~~~~~~~~~~~
618
\begin{code}
619
tyVarsOfType :: Type -> TyVarSet
620
tyVarsOfType (TyVarTy tv)		= unitVarSet tv
621
tyVarsOfType (TyConApp tycon tys)	= tyVarsOfTypes tys
622
tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
623
tyVarsOfType (PredTy sty)		= tyVarsOfPred sty
624
625
626
tyVarsOfType (FunTy arg res)		= tyVarsOfType arg `unionVarSet` tyVarsOfType res
tyVarsOfType (AppTy fun arg)		= tyVarsOfType fun `unionVarSet` tyVarsOfType arg
tyVarsOfType (ForAllTy tyvar ty)	= tyVarsOfType ty `minusVarSet` unitVarSet tyvar
627

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
-- 			Note [Syn]
-- Consider
--	type T a = Int
-- What are the free tyvars of (T x)?  Empty, of course!  
-- Here's the example that Ralf Laemmel showed me:
--	foo :: (forall a. C u a -> C u a) -> u
--	mappend :: Monoid u => u -> u -> u
--
--	bar :: Monoid u => u
--	bar = foo (\t -> t `mappend` t)
-- We have to generalise at the arg to f, and we don't
-- want to capture the constraint (Monad (C u a)) because
-- it appears to mention a.  Pretty silly, but it was useful to him.


643
tyVarsOfTypes :: [Type] -> TyVarSet
644
645
tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys

646
tyVarsOfPred :: PredType -> TyVarSet
647
648
tyVarsOfPred (IParam _ ty)  = tyVarsOfType ty
tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
649
650

tyVarsOfTheta :: ThetaType -> TyVarSet
651
tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
652

653
-- Add a Note with the free tyvars to the top of the type
654
addFreeTyVars :: Type -> Type
655
656
addFreeTyVars ty@(NoteTy (FTVNote _) _)      = ty
addFreeTyVars ty			     = NoteTy (FTVNote (tyVarsOfType ty)) ty
657
\end{code}
658

659
660
661
662
663
%************************************************************************
%*									*
\subsection{TidyType}
%*									*
%************************************************************************
664

665
666
tidyTy tidies up a type for printing in an error message, or in
an interface file.
667

668
It doesn't change the uniques at all, just the print names.
669
670

\begin{code}
671
672
673
tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidyTyVarBndr (tidy_env, subst) tyvar
  = case tidyOccName tidy_env (getOccName name) of
674
      (tidy', occ') -> 	((tidy', subst'), tyvar')
675
676
677
		    where
			subst' = extendVarEnv subst tyvar tyvar'
			tyvar' = setTyVarName tyvar name'
678
			name'  = mkInternalName (getUnique name) occ' noSrcLoc
679
680
				-- Note: make a *user* tyvar, so it printes nicely
				-- Could extract src loc, but no need.
681
682
  where
    name = tyVarName tyvar
683

684
685
686
tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
-- Add the free tyvars to the env in tidy form,
-- so that we can tidy the type they are free in
687
688
689
690
691
692
693
694
695
696
697
tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))

tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars

tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
-- Treat a new tyvar as a binder, and give it a fresh tidy name
tidyOpenTyVar env@(tidy_env, subst) tyvar
  = case lookupVarEnv subst tyvar of
	Just tyvar' -> (env, tyvar')		-- Already substituted
	Nothing	    -> tidyTyVarBndr env tyvar	-- Treat it as a binder
698

699
700
701
tidyType :: TidyEnv -> Type -> Type
tidyType env@(tidy_env, subst) ty
  = go ty
702
  where
703
704
705
    go (TyVarTy tv)	    = case lookupVarEnv subst tv of
				Nothing  -> TyVarTy tv
				Just tv' -> TyVarTy tv'
706
707
    go (TyConApp tycon tys) = let args = map go tys
			      in args `seqList` TyConApp tycon args
sof's avatar
sof committed
708
    go (NoteTy note ty)     = (NoteTy $! (go_note note)) $! (go ty)
709
    go (PredTy sty)	    = PredTy (tidyPred env sty)
sof's avatar
sof committed
710
711
712
    go (AppTy fun arg)	    = (AppTy $! (go fun)) $! (go arg)
    go (FunTy fun arg)	    = (FunTy $! (go fun)) $! (go arg)
    go (ForAllTy tv ty)	    = ForAllTy tvp $! (tidyType envp ty)
713
			      where
714
			        (envp, tvp) = tidyTyVarBndr env tv
715
716
717

    go_note note@(FTVNote ftvs) = note	-- No need to tidy the free tyvars

718
tidyTypes env tys = map (tidyType env) tys
719

720
721
722
tidyPred :: TidyEnv -> PredType -> PredType
tidyPred env (IParam n ty)     = IParam n (tidyType env ty)
tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
723
724
725
\end{code}


726
@tidyOpenType@ grabs the free type variables, tidies them
727
728
729
730
731
732
733
and then uses @tidyType@ to work over the type itself

\begin{code}
tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
tidyOpenType env ty
  = (env', tidyType env' ty)
  where
734
    env' = tidyFreeTyVars env (tyVarsOfType ty)
735
736
737
738
739
740

tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
tidyOpenTypes env tys = mapAccumL tidyOpenType env tys

tidyTopType :: Type -> Type
tidyTopType ty = tidyType emptyTidyEnv ty
741
742
\end{code}

743

744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
%************************************************************************
%*									*
		Tidying Kinds
%*									*
%************************************************************************

We use a grevious hack for tidying KindVars.  A TidyEnv contains
a (VarEnv Var) substitution, to express the renaming; but
KindVars are not Vars.  The Right Thing ultimately is to make them
into Vars (and perhaps make Kinds into Types), but I just do a hack
here: I make up a TyVar just to remember the new OccName for the
renamed KindVar

\begin{code}
tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
tidyKind env@(tidy_env, subst) (KindVar kvar)
  | Just tv <- lookupVarEnv_Directly subst uniq
  = (env, KindVar (setKindVarOcc kvar (getOccName tv)))
  | otherwise
  = ((tidy', subst'), KindVar kvar')
  where
    uniq = kindVarUniq kvar
    (tidy', occ') = tidyOccName tidy_env (kindVarOcc kvar)
    kvar'   = setKindVarOcc kvar occ'
    fake_tv = mkTyVar tv_name (panic "tidyKind:fake tv kind")
    tv_name = mkInternalName uniq occ' noSrcLoc
    subst'  = extendVarEnv subst fake_tv fake_tv

tidyKind env (FunKind k1 k2) 
  = (env2, FunKind k1' k2')
  where
    (env1, k1') = tidyKind env  k1
    (env2, k2') = tidyKind env1 k2

tidyKind env k = (env, k)	-- Atomic kinds
\end{code}

781

782
783
%************************************************************************
%*									*
784
\subsection{Liftedness}
785
786
787
%*									*
%************************************************************************

788
\begin{code}
789
isUnLiftedType :: Type -> Bool
790
791
792
793
794
795
	-- isUnLiftedType returns True for forall'd unlifted types:
	--	x :: forall a. Int#
	-- I found bindings like these were getting floated to the top level.
	-- They are pretty bogus types, mind you.  It would be better never to
	-- construct them

796
isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
797
798
799
isUnLiftedType (ForAllTy tv ty)  = isUnLiftedType ty
isUnLiftedType (TyConApp tc _)   = isUnLiftedTyCon tc
isUnLiftedType other		 = False	
800

801
isUnboxedTupleType :: Type -> Bool
802
803
804
isUnboxedTupleType ty = case splitTyConApp_maybe ty of
			   Just (tc, ty_args) -> isUnboxedTupleTyCon tc
			   other	      -> False
805

806
-- Should only be applied to *types*; hence the assert
807
isAlgType :: Type -> Bool
808
isAlgType ty = case splitTyConApp_maybe ty of
sof's avatar
sof committed
809
			Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
810
811
					      isAlgTyCon tc
			other		   -> False
812
813
\end{code}

814
815
816
817
818
819
820
821
@isStrictType@ computes whether an argument (or let RHS) should
be computed strictly or lazily, based only on its type.
Works just like isUnLiftedType, except that it has a special case 
for dictionaries.  Since it takes account of ClassP, you might think
this function should be in TcType, but isStrictType is used by DataCon,
which is below TcType in the hierarchy, so it's convenient to put it here.

\begin{code}
822
823
isStrictType (PredTy pred)     = isStrictPred pred
isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
824
825
826
827
828
829
isStrictType (ForAllTy tv ty)  = isStrictType ty
isStrictType (TyConApp tc _)   = isUnLiftedTyCon tc
isStrictType other	       = False	

isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
isStrictPred other	     = False
830
831
832
833
834
835
836
837
838
839
840
841
	-- We may be strict in dictionary types, but only if it 
	-- has more than one component.
	-- [Being strict in a single-component dictionary risks
	--  poking the dictionary component, which is wrong.]
\end{code}

\begin{code}
isPrimitiveType :: Type -> Bool
-- Returns types that are opaque to Haskell.
-- Most of these are unlifted, but now that we interact with .NET, we
-- may have primtive (foreign-imported) types that are lifted
isPrimitiveType ty = case splitTyConApp_maybe ty of
sof's avatar
sof committed
842
			Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
843
844
845
846
					      isPrimTyCon tc
			other		   -> False
\end{code}

847

848
849
850
851
852
853
854
855
856
857
858
859
%************************************************************************
%*									*
\subsection{Sequencing on types
%*									*
%************************************************************************

\begin{code}
seqType :: Type -> ()
seqType (TyVarTy tv) 	  = tv `seq` ()
seqType (AppTy t1 t2) 	  = seqType t1 `seq` seqType t2
seqType (FunTy t1 t2) 	  = seqType t1 `seq` seqType t2
seqType (NoteTy note t2)  = seqNote note `seq` seqType t2
860
seqType (PredTy p) 	  = seqPred p
861
862
863
864
865
866
867
868
869
seqType (TyConApp tc tys) = tc `seq` seqTypes tys
seqType (ForAllTy tv ty)  = tv `seq` seqType ty

seqTypes :: [Type] -> ()
seqTypes []       = ()
seqTypes (ty:tys) = seqType ty `seq` seqTypes tys

seqNote :: TyNote -> ()
seqNote (FTVNote set) = sizeUniqSet set `seq` ()
870

871
seqPred :: PredType -> ()
872
873
seqPred (ClassP c tys) = c  `seq` seqTypes tys
seqPred (IParam n ty)  = n  `seq` seqType ty
874
875
876
877
878
\end{code}


%************************************************************************
%*									*
879
		Equality for Core types 
880
	(We don't use instances so that we know where it happens)
881
882
883
%*									*
%************************************************************************

884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
Note that eqType works right even for partial applications of newtypes.
See Note [Newtype eta] in TyCon.lhs

\begin{code}
coreEqType :: Type -> Type -> Bool
coreEqType t1 t2
  = eq rn_env t1 t2
  where
    rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))

    eq env (TyVarTy tv1)       (TyVarTy tv2)     = rnOccL env tv1 == rnOccR env tv2
    eq env (ForAllTy tv1 t1)   (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
    eq env (AppTy s1 t1)       (AppTy s2 t2)     = eq env s1 s2 && eq env t1 t2
    eq env (FunTy s1 t1)       (FunTy s2 t2)     = eq env s1 s2 && eq env t1 t2
    eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
	| tc1 == tc2, all2 (eq env) tys1 tys2 = True
			-- The lengths should be equal because
			-- the two types have the same kind
	-- NB: if the type constructors differ that does not 
	--     necessarily mean that the types aren't equal
	--     (synonyms, newtypes)
	-- Even if the type constructors are the same, but the arguments
	-- differ, the two types could be the same (e.g. if the arg is just
	-- ignored in the RHS).  In both these cases we fall through to an 
	-- attempt to expand one side or the other.

	-- Now deal with newtypes, synonyms, pred-tys
    eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2
		 | Just t2' <- coreView t2 = eq env t1 t2'

	-- Fall through case; not equal!
    eq env t1 t2 = False
\end{code}
917

918

919
920
921
922
923
924
%************************************************************************
%*									*
		Comparision for source types 
	(We don't use instances so that we know where it happens)
%*									*
%************************************************************************
925

926
927
928
Note that 
	tcEqType, tcCmpType 
do *not* look through newtypes, PredTypes
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954

\begin{code}
tcEqType :: Type -> Type -> Bool
tcEqType t1 t2 = isEqual $ cmpType t1 t2

tcEqTypes :: [Type] -> [Type] -> Bool
tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2

tcCmpType :: Type -> Type -> Ordering
tcCmpType t1 t2 = cmpType t1 t2

tcCmpTypes :: [Type] -> [Type] -> Ordering
tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2

tcEqPred :: PredType -> PredType -> Bool
tcEqPred p1 p2 = isEqual $ cmpPred p1 p2

tcCmpPred :: PredType -> PredType -> Ordering
tcCmpPred p1 p2 = cmpPred p1 p2

tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
\end{code}

Now here comes the real worker

955
\begin{code}
956
957
958
959
960
961
962
963
964
965
966
967
968
969
cmpType :: Type -> Type -> Ordering
cmpType t1 t2 = cmpTypeX rn_env t1 t2
  where
    rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))

cmpTypes :: [Type] -> [Type] -> Ordering
cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
  where
    rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))

cmpPred :: PredType -> PredType -> Ordering
cmpPred p1 p2 = cmpPredX rn_env p1 p2
  where
    rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
970

971
cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering	-- Main workhorse
972
973
cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
		   | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
974

975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
cmpTypeX env (TyVarTy tv1)       (TyVarTy tv2)       = rnOccL env tv1 `compare` rnOccR env tv2
cmpTypeX env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
cmpTypeX env (AppTy s1 t1)       (AppTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
cmpTypeX env (FunTy s1 t1)       (FunTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
cmpTypeX env (PredTy p1)         (PredTy p2)         = cmpPredX env p1 p2
cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
cmpTypeX env t1			(NoteTy _ t2)	     = cmpTypeX env t1 t2

    -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
cmpTypeX env (AppTy _ _) (TyVarTy _) = GT
    
cmpTypeX env (FunTy _ _) (TyVarTy _) = GT
cmpTypeX env (FunTy _ _) (AppTy _ _) = GT
    
cmpTypeX env (TyConApp _ _) (TyVarTy _) = GT
cmpTypeX env (TyConApp _ _) (AppTy _ _) = GT
cmpTypeX env (TyConApp _ _) (FunTy _ _) = GT
    
cmpTypeX env (ForAllTy _ _) (TyVarTy _)    = GT
cmpTypeX env (ForAllTy _ _) (AppTy _ _)    = GT
cmpTypeX env (ForAllTy _ _) (FunTy _ _)    = GT
cmpTypeX env (ForAllTy _ _) (TyConApp _ _) = GT

cmpTypeX env (PredTy _)   t2		= GT

cmpTypeX env _ _ = LT

-------------
cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
cmpTypesX env []        []        = EQ
1005
cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
cmpTypesX env []        tys       = LT
cmpTypesX env ty        []        = GT

-------------
cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
	-- Compare types as well as names for implicit parameters
	-- This comparison is used exclusively (I think) for the
	-- finite map built in TcSimplify
cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` cmpTypesX env tys1 tys2
1016
cmpPredX env (IParam _ _)     (ClassP _ _)     = LT
1017
1018
1019
1020
1021
1022
1023
1024
1025
cmpPredX env (ClassP _ _)     (IParam _ _)     = GT
\end{code}

PredTypes are used as a FM key in TcSimplify, 
so we take the easy path and make them an instance of Ord

\begin{code}
instance Eq  PredType where { (==)    = tcEqPred }
instance Ord PredType where { compare = tcCmpPred }
1026
1027
\end{code}

1028
1029
1030
1031
1032
1033
1034
1035
1036
1037

%************************************************************************
%*									*
		Type substitutions
%*									*
%************************************************************************

\begin{code}
data TvSubst 		
  = TvSubst InScopeSet 	-- The in-scope type variables
1038
	    TvSubstEnv	-- The substitution itself
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
			-- See Note [Apply Once]

{- ----------------------------------------------------------
	 	Note [Apply Once]

We use TvSubsts to instantiate things, and we might instantiate
	forall a b. ty
\with the types
	[a, b], or [b, a].
So the substition might go [a->b, b->a].  A similar situation arises in Core
when we find a beta redex like
	(/\ a /\ b -> e) b a
Then we also end up with a substition that permutes type variables. Other
variations happen to; for example [a -> (a, b)].  

	***************************************************
	*** So a TvSubst must be applied precisely once ***
	***************************************************

A TvSubst is not idempotent, but, unlike the non-idempotent substitution
we use during unifications, it must not be repeatedly applied.
-------------------------------------------------------------- -}


type TvSubstEnv = TyVarEnv Type
	-- A TvSubstEnv is used both inside a TvSubst (with the apply-once
	-- invariant discussed in Note [Apply Once]), and also independently
	-- in the middle of matching, and unification (see Types.Unify)
	-- So you have to look at the context to know if it's idempotent or
	-- apply-once or whatever
1069
1070
emptyTvSubstEnv :: TvSubstEnv
emptyTvSubstEnv = emptyVarEnv
1071

1072
1073
1074
composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
-- (compose env1 env2)(x) is env1(env2(x)); i.e. apply env2 then env1
-- It assumes that both are idempotent
1075
-- Typically, env1 is the refinement to a base substitution env2
1076
1077
1078
1079
1080
composeTvSubst in_scope env1 env2
  = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
	-- First apply env1 to the range of env2
	-- Then combine the two, making sure that env1 loses if
	-- both bind the same variable; that's why env1 is the
1081
	--  *left* argument to plusVarEnv, because the right arg wins
1082
1083
1084
  where
    subst1 = TvSubst in_scope env1

1085
emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1086

1087
1088
1089
isEmptyTvSubst :: TvSubst -> Bool
isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env

1090
1091
1092
mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
mkTvSubst = TvSubst

1093
1094
1095
1096
1097
1098
1099
1100
1101
getTvSubstEnv :: TvSubst -> TvSubstEnv
getTvSubstEnv (TvSubst _ env) = env

getTvInScope :: TvSubst -> InScopeSet
getTvInScope (TvSubst in_scope _) = in_scope

isInScope :: Var -> TvSubst -> Bool
isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope

1102
1103
1104
notElemTvSubst :: TyVar -> TvSubst -> Bool
notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)

1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env

extendTvInScope :: TvSubst -> [Var] -> TvSubst
extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env

extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)

extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
extendTvSubstList (TvSubst in_scope env) tvs tys 
  = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))

1118
-- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1119
1120
1121
-- the types given; but it's just a thunk so with a bit of luck
-- it'll never be evaluated

1122
1123
mkOpenTvSubst :: TvSubstEnv -> TvSubst
mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1124

1125
1126
zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
zipOpenTvSubst tyvars tys 
1127
1128
1129
1130
1131
#ifdef DEBUG
  | length tyvars /= length tys
  = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
  | otherwise
#endif
1132
1133
1134
1135
1136
1137
1138
1139
1140
  = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)

-- mkTopTvSubst is called when doing top-level substitutions.
-- Here we expect that the free vars of the range of the
-- substitution will be empty.
mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)

zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1141
1142
1143
1144
1145
1146
1147
zipTopTvSubst tyvars tys 
#ifdef DEBUG
  | length tyvars /= length tys
  = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
  | otherwise
#endif
  = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173

zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
zipTyEnv tyvars tys
#ifdef DEBUG
  | length tyvars /= length tys
  = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
  | otherwise
#endif
  = zip_ty_env tyvars tys emptyVarEnv

-- Later substitutions in the list over-ride earlier ones, 
-- but there should be no loops
zip_ty_env []       []       env = env
zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
	-- There used to be a special case for when 
	--	ty == TyVarTy tv
	-- (a not-uncommon case) in which case the substitution was dropped.
	-- But the type-tidier changes the print-name of a type variable without
	-- changing the unique, and that led to a bug.   Why?  Pre-tidying, we had 
	-- a type {Foo t}, where Foo is a one-method class.  So Foo is really a newtype.
	-- And it happened that t was the type variable of the class.  Post-tiding, 
	-- it got turned into {Foo t2}.  The ext-core printer expanded this using
	-- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
	-- and so generated a rep type mentioning t not t2.  
	--
	-- Simplest fix is to nuke the "optimisation"
1174
1175
zip_ty_env tvs      tys      env   = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
-- zip_ty_env _ _ env = env
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191

instance Outputable TvSubst where
  ppr (TvSubst ins env) 
    = sep[ ptext SLIT("<TvSubst"),
	   nest 2 (ptext SLIT("In scope:") <+> ppr ins), 
	   nest 2 (ptext SLIT("Env:") <+> ppr env) ]
\end{code}

%************************************************************************
%*									*
		Performing type substitutions
%*									*
%************************************************************************

\begin{code}
substTyWith :: [TyVar] -> [Type] -> Type -> Type
1192
1193
substTyWith tvs tys = ASSERT( length tvs == length tys )
		      substTy (zipOpenTvSubst tvs tys)
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211

substTy :: TvSubst -> Type  -> Type
substTy subst ty | isEmptyTvSubst subst = ty
		 | otherwise	        = subst_ty subst ty

substTys :: TvSubst -> [Type] -> [Type]
substTys subst tys | isEmptyTvSubst subst = tys
	           | otherwise	          = map (subst_ty subst) tys

substTheta :: TvSubst -> ThetaType -> ThetaType
substTheta subst theta
  | isEmptyTvSubst subst = theta
  | otherwise	         = map (substPred subst) theta

substPred :: TvSubst -> PredType -> PredType
substPred subst (IParam n ty)     = IParam n (subst_ty subst ty)