Type.lhs 31.7 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
10
	TyThing(..),
	Type, PredType(..), ThetaType,
11
	Kind, TyVarSubst, 
12

13
	superKind, superBoxity,				-- KX and BX respectively
14
	liftedBoxity, unliftedBoxity, 			-- :: BX
15
16
	openKindCon, 					-- :: KX
	typeCon,					-- :: BX -> KX
17
	liftedTypeKind, unliftedTypeKind, openTypeKind,	-- :: KX
18
	mkArrowKind, mkArrowKinds,			-- :: KX -> KX -> KX
19
	isTypeKind, isAnyTypeKind,
20
	funTyCon,
21

22
        -- exports from this module:
23
        hasMoreBoxityInfo, defaultKind,
24

25
26
	mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,

27
	mkAppTy, mkAppTys, splitAppTy, splitAppTys, splitAppTy_maybe,
28

29
	mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, splitFunTys, 
30
	funResultTy, funArgTy, zipFunTys, isFunTy,
31

32
	mkGenTyConApp, mkTyConApp, mkTyConTy, 
33
34
	tyConAppTyCon, tyConAppArgs, 
	splitTyConApp_maybe, splitTyConApp,
35

36
	mkSynTy, 
37

38
	repType, typePrimRep,
39

40
	mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, 
41
	applyTy, applyTys, isForAllTy, dropForAlls,
42

43
	-- Source types
44
	predTypeRep, mkPredTy, mkPredTys,
45

46
	-- Newtypes
47
	splitRecNewType_maybe,
48

49
	-- Lifting and boxity
50
51
	isUnLiftedType, isUnboxedTupleType, isAlgType, isPrimitiveType,
	isStrictType, isStrictPred, 
52

53
	-- Free variables
54
	tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
55
	typeKind, addFreeTyVars,
56

57
	-- Tidying up for printing
58
59
60
61
62
	tidyType,      tidyTypes,
	tidyOpenType,  tidyOpenTypes,
	tidyTyVarBndr, tidyFreeTyVars,
	tidyOpenTyVar, tidyOpenTyVars,
	tidyTopType,   tidyPred,
63

64
	-- Comparison
65
	eqType, eqKind, 
66

67
68
69
	-- Seq
	seqType, seqTypes

70
    ) where
71

72
73
#include "HsVersions.h"

74
75
76
77
78
79
80
-- We import the representation and primitive functions from TypeRep.
-- Many things are reexported, but not the representation!

import TypeRep

-- Other imports:

81
import {-# SOURCE #-}   Subst  ( substTyWith )
82
83

-- friends:
84
import Var	( TyVar, tyVarKind, tyVarName, setTyVarName )
85
86
87
import VarEnv
import VarSet

88
import Name	( NamedThing(..), mkInternalName, tidyOccName )
89
import Class	( Class, classTyCon )
90
import TyCon	( TyCon, isRecursiveTyCon, isPrimTyCon,
91
		  isUnboxedTupleTyCon, isUnLiftedTyCon,
92
		  isFunTyCon, isNewTyCon, newTyConRep,
93
94
95
		  isAlgTyCon, isSynTyCon, tyConArity, 
	          tyConKind, getSynTyConDefn,
		  tyConPrimRep, 
96
97
		)

98
-- others
99
import CmdLineOpts	( opt_DictsStrict )
100
import SrcLoc		( noSrcLoc )
101
import PrimRep		( PrimRep(..) )
102
import Unique		( Uniquable(..) )
103
import Util		( mapAccumL, seqList, lengthIs, snocView )
104
import Outputable
105
import UniqSet		( sizeUniqSet )		-- Should come via VarSet
106
import Maybe		( isJust )
107
108
\end{code}

109
110
111

%************************************************************************
%*									*
112
\subsection{Stuff to do with kinds.}
113
114
115
116
%*									*
%************************************************************************

\begin{code}
117
hasMoreBoxityInfo :: Kind -> Kind -> Bool
118
-- (k1 `hasMoreBoxityInfo` k2) checks that k1 <: k2
119
hasMoreBoxityInfo k1 k2
120
  | k2 `eqKind` openTypeKind = isAnyTypeKind k1
121
  | otherwise	  	     = k1 `eqKind` k2
122
123
124
125
126
127

isAnyTypeKind :: Kind -> Bool
-- True of kind * and *# and ?
isAnyTypeKind (TyConApp tc _) = tc == typeCon || tc == openKindCon
isAnyTypeKind (NoteTy _ k)    = isAnyTypeKind k
isAnyTypeKind other	      = False
128
129
130
131
132
133

isTypeKind :: Kind -> Bool
-- True of kind * and *#
isTypeKind (TyConApp tc _) = tc == typeCon
isTypeKind (NoteTy _ k)    = isTypeKind k
isTypeKind other	   = False
134
135
136

defaultKind :: Kind -> Kind
-- Used when generalising: default kind '?' to '*'
137
138
defaultKind kind | kind `eqKind` openTypeKind = liftedTypeKind
	         | otherwise	 	      = kind
139
\end{code}
140
141


142
143
144
145
146
%************************************************************************
%*									*
\subsection{Constructor-specific functions}
%*									*
%************************************************************************
sof's avatar
sof committed
147
148


149
150
151
---------------------------------------------------------------------
				TyVarTy
				~~~~~~~
152
\begin{code}
153
mkTyVarTy  :: TyVar   -> Type
154
mkTyVarTy  = TyVarTy
155

156
mkTyVarTys :: [TyVar] -> [Type]
157
mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
158

159
getTyVar :: String -> Type -> TyVar
160
161
162
getTyVar msg ty = case getTyVar_maybe ty of
		    Just tv -> tv
		    Nothing -> panic ("getTyVar: " ++ msg)
163

164
isTyVarTy :: Type -> Bool
165
166
167
168
169
170
171
172
isTyVarTy ty = isJust (getTyVar_maybe ty)

getTyVar_maybe :: Type -> Maybe TyVar
getTyVar_maybe (TyVarTy tv) 	 = Just tv
getTyVar_maybe (NoteTy _ t) 	 = getTyVar_maybe t
getTyVar_maybe (PredTy p) 	 = getTyVar_maybe (predTypeRep p)
getTyVar_maybe (NewTcApp tc tys) = getTyVar_maybe (newTypeRep tc tys)
getTyVar_maybe other	         = Nothing
173
174
175
\end{code}


176
177
178
179
180
181
---------------------------------------------------------------------
				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.
182

183
\begin{code}
184
mkAppTy orig_ty1 orig_ty2
185
  = mk_app orig_ty1
186
  where
187
    mk_app (NoteTy _ ty1)    = mk_app ty1
188
    mk_app (NewTcApp tc tys) = NewTcApp tc (tys ++ [orig_ty2])
189
    mk_app (TyConApp tc tys) = mkGenTyConApp tc (tys ++ [orig_ty2])
190
    mk_app ty1		     = AppTy orig_ty1 orig_ty2
191
192
193
194
195
196
197
198
	-- 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
199

200
mkAppTys :: Type -> [Type] -> Type
201
202
mkAppTys orig_ty1 []	    = orig_ty1
	-- This check for an empty list of type arguments
203
	-- avoids the needless loss of a type synonym constructor.
204
205
206
	-- For example: mkAppTys Rational []
	--   returns to (Ratio Integer), which has needlessly lost
	--   the Rational part.
207
mkAppTys orig_ty1 orig_tys2
208
  = mk_app orig_ty1
209
  where
210
    mk_app (NoteTy _ ty1)    = mk_app ty1
211
    mk_app (NewTcApp tc tys) = NewTcApp tc (tys ++ orig_tys2)
212
    mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
213
				-- Use mkTyConApp in case tc is (->)
214
    mk_app ty1		     = foldl AppTy orig_ty1 orig_tys2
215

216
splitAppTy_maybe :: Type -> Maybe (Type, Type)
217
splitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
218
219
splitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
splitAppTy_maybe (NoteTy _ ty)     = splitAppTy_maybe ty
220
221
splitAppTy_maybe (PredTy p)        = splitAppTy_maybe (predTypeRep p)
splitAppTy_maybe (NewTcApp tc tys) = splitAppTy_maybe (newTypeRep tc tys)
222
223
splitAppTy_maybe (TyConApp tc tys) = case snocView tys of
					Nothing -> Nothing
224
225
226
					Just (tys',ty') -> Just (mkGenTyConApp tc tys', ty')
						-- mkGenTyConApp just in case the tc is a newtype

227
splitAppTy_maybe other	     	   = Nothing
228

229
splitAppTy :: Type -> (Type, Type)
230
231
232
splitAppTy ty = case splitAppTy_maybe ty of
			Just pr -> pr
			Nothing -> panic "splitAppTy"
233

234
splitAppTys :: Type -> (Type, [Type])
235
splitAppTys ty = split ty ty []
236
  where
237
    split orig_ty (AppTy ty arg)        args = split ty ty (arg:args)
238
    split orig_ty (NoteTy _ ty)         args = split orig_ty ty args
239
240
241
242
    split orig_ty (PredTy p)            args = split orig_ty (predTypeRep p) args
    split orig_ty (NewTcApp tc tc_args) args = split orig_ty (newTypeRep tc tc_args) args
    split orig_ty (TyConApp tc tc_args) args = (mkGenTyConApp tc [], tc_args ++ args)
						-- mkGenTyConApp just in case the tc is a newtype
243
    split orig_ty (FunTy ty1 ty2)       args = ASSERT( null args )
244
					       (TyConApp funTyCon [], [ty1,ty2])
245
    split orig_ty ty		        args = (orig_ty, args)
246
247
\end{code}

248
249
250
251
252

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

253
\begin{code}
254
mkFunTy :: Type -> Type -> Type
255
mkFunTy arg res = FunTy arg res
256

257
mkFunTys :: [Type] -> Type -> Type
258
mkFunTys tys ty = foldr FunTy ty tys
259

260
261
262
isFunTy :: Type -> Bool 
isFunTy ty = isJust (splitFunTy_maybe ty)

263
splitFunTy :: Type -> (Type, Type)
264
265
266
267
268
splitFunTy (FunTy arg res)   = (arg, res)
splitFunTy (NoteTy _ ty)     = splitFunTy ty
splitFunTy (PredTy p)        = splitFunTy (predTypeRep p)
splitFunTy (NewTcApp tc tys) = splitFunTy (newTypeRep tc tys)
splitFunTy other	     = pprPanic "splitFunTy" (crudePprType other)
269

270
splitFunTy_maybe :: Type -> Maybe (Type, Type)
271
272
273
274
275
splitFunTy_maybe (FunTy arg res)   = Just (arg, res)
splitFunTy_maybe (NoteTy _ ty)     = splitFunTy_maybe ty
splitFunTy_maybe (PredTy p)        = splitFunTy_maybe (predTypeRep p)
splitFunTy_maybe (NewTcApp tc tys) = splitFunTy_maybe (newTypeRep tc tys)
splitFunTy_maybe other	           = Nothing
276

277
splitFunTys :: Type -> ([Type], Type)
278
splitFunTys ty = split [] ty ty
279
  where
280
281
282
283
284
    split args orig_ty (FunTy arg res) 	 = split (arg:args) res res
    split args orig_ty (NoteTy _ ty)   	 = split args orig_ty ty
    split args orig_ty (PredTy p)     	 = split args orig_ty (predTypeRep p)
    split args orig_ty (NewTcApp tc tys) = split args orig_ty (newTypeRep tc tys)
    split args orig_ty ty                = (reverse args, orig_ty)
285

286
287
288
zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
  where
289
290
291
292
293
294
    split acc []     nty ty  	           = (reverse acc, nty)
    split acc (x:xs) nty (FunTy arg res)   = split ((x,arg):acc) xs res res
    split acc xs     nty (NoteTy _ ty)     = split acc           xs nty ty
    split acc xs     nty (PredTy p)        = split acc           xs nty (predTypeRep p)
    split acc xs     nty (NewTcApp tc tys) = split acc           xs nty (newTypeRep tc tys)
    split acc (x:xs) nty ty                = pprPanic "zipFunTys" (ppr orig_xs <+> crudePprType orig_ty)
295
296
    
funResultTy :: Type -> Type
297
298
299
300
301
funResultTy (FunTy arg res)   = res
funResultTy (NoteTy _ ty)     = funResultTy ty
funResultTy (PredTy p)        = funResultTy (predTypeRep p)
funResultTy (NewTcApp tc tys) = funResultTy (newTypeRep tc tys)
funResultTy ty		      = pprPanic "funResultTy" (crudePprType ty)
302
303

funArgTy :: Type -> Type
304
305
306
307
308
funArgTy (FunTy arg res)   = arg
funArgTy (NoteTy _ ty)     = funArgTy ty
funArgTy (PredTy p)        = funArgTy (predTypeRep p)
funArgTy (NewTcApp tc tys) = funArgTy (newTypeRep tc tys)
funArgTy ty		   = pprPanic "funArgTy" (crudePprType ty)
309
310
311
\end{code}


312
313
314
---------------------------------------------------------------------
				TyConApp
				~~~~~~~~
315
@mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or PredTy,
316
as apppropriate.
317

318
\begin{code}
319
320
321
322
323
mkGenTyConApp :: TyCon -> [Type] -> Type
mkGenTyConApp tc tys
  | isSynTyCon tc = mkSynTy tc tys
  | otherwise     = mkTyConApp tc tys

324
mkTyConApp :: TyCon -> [Type] -> Type
325
-- Assumes TyCon is not a SynTyCon; use mkSynTy instead for those
326
mkTyConApp tycon tys
327
  | isFunTyCon tycon, [ty1,ty2] <- tys
328
  = FunTy ty1 ty2
329

330
331
  | isNewTyCon tycon
  = NewTcApp tycon tys
332
333
334
335
336

  | otherwise
  = ASSERT(not (isSynTyCon tycon))
    TyConApp tycon tys

337
mkTyConTy :: TyCon -> Type
338
mkTyConTy tycon = mkTyConApp tycon []
339
340
341
342
343

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

344
tyConAppTyCon :: Type -> TyCon
345
tyConAppTyCon ty = fst (splitTyConApp ty)
346
347

tyConAppArgs :: Type -> [Type]
348
tyConAppArgs ty = snd (splitTyConApp ty)
349
350
351
352

splitTyConApp :: Type -> (TyCon, [Type])
splitTyConApp ty = case splitTyConApp_maybe ty of
			Just stuff -> stuff
353
			Nothing	   -> pprPanic "splitTyConApp" (crudePprType ty)
354

355
splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
356
splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
357
splitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
358
splitTyConApp_maybe (NoteTy _ ty)     = splitTyConApp_maybe ty
359
360
splitTyConApp_maybe (PredTy p)        = splitTyConApp_maybe (predTypeRep p)
splitTyConApp_maybe (NewTcApp tc tys) = splitTyConApp_maybe (newTypeRep tc tys)
361
splitTyConApp_maybe other	      = Nothing
sof's avatar
sof committed
362
\end{code}
363

364

365
366
367
368
---------------------------------------------------------------------
				SynTy
				~~~~~

369
\begin{code}
370
371
372
373
mkSynTy tycon tys
  | n_args == arity	-- Exactly saturated
  = mk_syn tys
  | n_args >  arity	-- Over-saturated
374
375
376
377
  = 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!
378
379
380
381
382
383
384
385
  | 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.

386
  where
387
388
389
390
391
392
    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
393
394
\end{code}

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

400
401
402
403
404
405
406
407
	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.
408
409


410
411
		Representation types
		~~~~~~~~~~~~~~~~~~~~
412
413
repType looks through 
	(a) for-alls, and
414
415
416
	(b) synonyms
	(c) predicates
	(d) usage annotations
417
	(e) [recursive] newtypes
418
It's useful in the back end.
419
420
421

\begin{code}
repType :: Type -> Type
422
-- Only applied to types of kind *; hence tycons are saturated
423
424
repType (ForAllTy _ ty)   = repType ty
repType (NoteTy   _ ty)   = repType ty
425
426
427
repType (PredTy  p)       = repType (predTypeRep p)
repType (NewTcApp tc tys) = ASSERT( tys `lengthIs` tyConArity tc )
			    repType (new_type_rep tc tys)
428
repType ty	 	  = ty
429

430
431
432
433
434
435
436

typePrimRep :: Type -> PrimRep
typePrimRep ty = case repType ty of
		   TyConApp tc _ -> tyConPrimRep tc
		   FunTy _ _	 -> PtrRep
		   AppTy _ _	 -> PtrRep	-- ??
		   TyVarTy _	 -> PtrRep
437
		   other	 -> pprPanic "typePrimRep" (crudePprType ty)
438
439
440
\end{code}


441

442
443
444
---------------------------------------------------------------------
				ForAllTy
				~~~~~~~~
445
446

\begin{code}
447
mkForAllTy :: TyVar -> Type -> Type
448
449
mkForAllTy tyvar ty
  = mkForAllTys [tyvar] ty
450

451
mkForAllTys :: [TyVar] -> Type -> Type
452
mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
453
454
455
456
457

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

459
splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
460
splitForAllTy_maybe ty = splitFAT_m ty
461
  where
462
    splitFAT_m (NoteTy _ ty)		= splitFAT_m ty
463
464
    splitFAT_m (PredTy p)		= splitFAT_m (predTypeRep p)
    splitFAT_m (NewTcApp tc tys)	= splitFAT_m (newTypeRep tc tys)
465
466
    splitFAT_m (ForAllTy tyvar ty)	= Just(tyvar, ty)
    splitFAT_m _			= Nothing
sof's avatar
sof committed
467

468
splitForAllTys :: Type -> ([TyVar], Type)
469
splitForAllTys ty = split ty ty []
470
   where
471
472
473
474
475
     split orig_ty (ForAllTy tv ty)  tvs = split ty ty (tv:tvs)
     split orig_ty (NoteTy _ ty)     tvs = split orig_ty ty tvs
     split orig_ty (PredTy p)	     tvs = split orig_ty (predTypeRep p) tvs
     split orig_ty (NewTcApp tc tys) tvs = split orig_ty (newTypeRep tc tys) tvs
     split orig_ty t		     tvs = (reverse tvs, orig_ty)
476
477
478

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

481
-- (mkPiType now in CoreUtils)
482

483
484
485
486
487
488
489
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. 
490

491
\begin{code}
492
applyTy :: Type -> Type -> Type
493
494
495
496
497
applyTy (PredTy p) 	  arg = applyTy (predTypeRep p) arg
applyTy (NewTcApp tc tys) arg = applyTy (newTypeRep tc tys) arg
applyTy (NoteTy _ fun)    arg = applyTy fun arg
applyTy (ForAllTy tv ty)  arg = substTyWith [tv] [arg] ty
applyTy other		  arg = panic "applyTy"
498

499
applyTys :: Type -> [Type] -> Type
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
-- 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
519
  = ASSERT2( n_tvs > 0, crudePprType orig_fun_ty )	-- Zero case gives infnite loop!
520
521
522
523
524
525
    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     
526
\end{code}
527

528

529
530
%************************************************************************
%*									*
531
\subsection{Source types}
532
533
%*									*
%************************************************************************
534

535
536
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.
537

538
Source types are always lifted.
539

540
The key function is predTypeRep which gives the representation of a source type:
541
542

\begin{code}
543
mkPredTy :: PredType -> Type
544
mkPredTy pred = PredTy pred
545
546

mkPredTys :: ThetaType -> [Type]
547
548
549
550
551
552
553
554
555
556
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.
predTypeRep (IParam _ ty)     = ty
predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
	-- Result might be a NewTcApp, but the consumer will
	-- look through that too if necessary
\end{code}
557
558


559
560
561
562
563
%************************************************************************
%*									*
		NewTypes
%*									*
%************************************************************************
564

565
566
567
568
569
570
571
572
573
574
575
576
577
\begin{code}
splitRecNewType_maybe :: Type -> Maybe Type
-- Newtypes are always represented by a NewTcApp
-- Sometimes we want to look through a recursive newtype, and that's what happens here
-- Only applied to types of kind *, hence the newtype is always saturated
splitRecNewType_maybe (NoteTy _ ty) = splitRecNewType_maybe ty  
splitRecNewType_maybe (NewTcApp tc tys)
  | isRecursiveTyCon tc
  = ASSERT( tys `lengthIs` tyConArity tc && isNewTyCon tc )
	-- The assert should hold because repType should
	-- only be applied to *types* (of kind *)
    Just (new_type_rep tc tys)
splitRecNewType_maybe other = Nothing
578
			
579
580
-----------------------------
newTypeRep :: TyCon -> [Type] -> Type
581
-- A local helper function (not exported)
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
-- Expands a newtype application to 
--	*either* a vanilla TyConApp (recursive newtype, or non-saturated)
--	*or*     the newtype representation (otherwise)
-- Either way, the result is not a NewTcApp
--
-- NB: the returned TyConApp is always deconstructed immediately by the 
--     caller... a TyConApp with a newtype type constructor never lives
--     in an ordinary type
newTypeRep tc tys
  | not (isRecursiveTyCon tc),		-- Not recursive and saturated
    tys `lengthIs` tyConArity tc 	-- treat as equivalent to expansion
  = new_type_rep tc tys
  | otherwise
  = TyConApp tc tys
	-- ToDo: Consider caching this substitution in a NType

----------------------------
-- 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
604
605
\end{code}

606

607
608
609
610
611
612
613
614
615
%************************************************************************
%*									*
\subsection{Kinds and free variables}
%*									*
%************************************************************************

---------------------------------------------------------------------
		Finding the kind of a type
		~~~~~~~~~~~~~~~~~~~~~~~~~~
616
\begin{code}
617
typeKind :: Type -> Kind
618

619
typeKind (TyVarTy tyvar)	= tyVarKind tyvar
620
typeKind (TyConApp tycon tys)	= foldr (\_ k -> funResultTy k) (tyConKind tycon) tys
621
typeKind (NewTcApp tycon tys)	= foldr (\_ k -> funResultTy k) (tyConKind tycon) tys
622
typeKind (NoteTy _ ty)		= typeKind ty
623
typeKind (PredTy _)		= liftedTypeKind -- Predicates are always 
624
						 -- represented by lifted types
625
typeKind (AppTy fun arg)	= funResultTy (typeKind fun)
626

627
628
typeKind (FunTy arg res)	= fix_up (typeKind res)
				where
629
				  fix_up (TyConApp tycon _) |  tycon == typeCon
630
							    || tycon == openKindCon = liftedTypeKind
631
632
				  fix_up (NoteTy _ kind) = fix_up kind
				  fix_up kind	         = kind
633
634
		-- The basic story is 
		-- 	typeKind (FunTy arg res) = typeKind res
635
		-- But a function is lifted regardless of its result type
636
637
638
		-- Hence the strange fix-up.
		-- Note that 'res', being the result of a FunTy, can't have 
		-- a strange kind like (*->*).
639
640

typeKind (ForAllTy tv ty)	= typeKind ty
641
642
643
\end{code}


644
645
646
---------------------------------------------------------------------
		Free variables of a type
		~~~~~~~~~~~~~~~~~~~~~~~~
647
\begin{code}
648
tyVarsOfType :: Type -> TyVarSet
649
tyVarsOfType (TyVarTy tv)		= unitVarSet tv
650
tyVarsOfType (TyConApp tycon tys)	= tyVarsOfTypes tys
651
tyVarsOfType (NewTcApp tycon tys)	= tyVarsOfTypes tys
652
tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
653
tyVarsOfType (NoteTy (SynNote ty1) ty2)	= tyVarsOfType ty2	-- See note [Syn] below
654
tyVarsOfType (PredTy sty)		= tyVarsOfPred sty
655
656
657
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
658

659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
-- 			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.


674
tyVarsOfTypes :: [Type] -> TyVarSet
675
676
tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys

677
tyVarsOfPred :: PredType -> TyVarSet
678
679
tyVarsOfPred (IParam _ ty)  = tyVarsOfType ty
tyVarsOfPred (ClassP _ tys) = tyVarsOfTypes tys
680
681

tyVarsOfTheta :: ThetaType -> TyVarSet
682
tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
683

684
-- Add a Note with the free tyvars to the top of the type
685
addFreeTyVars :: Type -> Type
686
687
addFreeTyVars ty@(NoteTy (FTVNote _) _)      = ty
addFreeTyVars ty			     = NoteTy (FTVNote (tyVarsOfType ty)) ty
688
\end{code}
689

690
691
692
693
694
%************************************************************************
%*									*
\subsection{TidyType}
%*									*
%************************************************************************
695

696
697
tidyTy tidies up a type for printing in an error message, or in
an interface file.
698

699
It doesn't change the uniques at all, just the print names.
700
701

\begin{code}
702
703
704
705
706
707
708
709
tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidyTyVarBndr (tidy_env, subst) tyvar
  = case tidyOccName tidy_env (getOccName name) of
      (tidy', occ') -> 	-- New occname reqd
			((tidy', subst'), tyvar')
		    where
			subst' = extendVarEnv subst tyvar tyvar'
			tyvar' = setTyVarName tyvar name'
710
			name'  = mkInternalName (getUnique name) occ' noSrcLoc
711
712
				-- Note: make a *user* tyvar, so it printes nicely
				-- Could extract src loc, but no need.
713
714
  where
    name = tyVarName tyvar
715

716
717
718
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
719
720
721
722
723
724
725
726
727
728
729
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
730

731
732
733
tidyType :: TidyEnv -> Type -> Type
tidyType env@(tidy_env, subst) ty
  = go ty
734
  where
735
736
737
    go (TyVarTy tv)	    = case lookupVarEnv subst tv of
				Nothing  -> TyVarTy tv
				Just tv' -> TyVarTy tv'
738
739
    go (TyConApp tycon tys) = let args = map go tys
			      in args `seqList` TyConApp tycon args
740
741
    go (NewTcApp tycon tys) = let args = map go tys
			      in args `seqList` NewTcApp tycon args
sof's avatar
sof committed
742
    go (NoteTy note ty)     = (NoteTy $! (go_note note)) $! (go ty)
743
    go (PredTy sty)	    = PredTy (tidyPred env sty)
sof's avatar
sof committed
744
745
746
    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)
747
			      where
748
			        (envp, tvp) = tidyTyVarBndr env tv
749

sof's avatar
sof committed
750
    go_note (SynNote ty)        = SynNote $! (go ty)
751
752
    go_note note@(FTVNote ftvs) = note	-- No need to tidy the free tyvars

753
tidyTypes env tys = map (tidyType env) tys
754

755
756
757
tidyPred :: TidyEnv -> PredType -> PredType
tidyPred env (IParam n ty)     = IParam n (tidyType env ty)
tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
758
759
760
\end{code}


761
@tidyOpenType@ grabs the free type variables, tidies them
762
763
764
765
766
767
768
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
769
    env' = tidyFreeTyVars env (tyVarsOfType ty)
770
771
772
773
774
775

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

tidyTopType :: Type -> Type
tidyTopType ty = tidyType emptyTidyEnv ty
776
777
\end{code}

778

779

780
781
%************************************************************************
%*									*
782
\subsection{Liftedness}
783
784
785
%*									*
%************************************************************************

786
\begin{code}
787
isUnLiftedType :: Type -> Bool
788
789
790
791
792
793
	-- 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

794
795
796
797
798
799
isUnLiftedType (ForAllTy tv ty)  = isUnLiftedType ty
isUnLiftedType (NoteTy _ ty)	 = isUnLiftedType ty
isUnLiftedType (TyConApp tc _)   = isUnLiftedTyCon tc
isUnLiftedType (PredTy _)	 = False		-- All source types are lifted
isUnLiftedType (NewTcApp tc tys) = isUnLiftedType (newTypeRep tc tys)
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
824
825
826
827
828
829
830
isStrictType (ForAllTy tv ty)  = isStrictType ty
isStrictType (NoteTy _ ty)     = isStrictType ty
isStrictType (TyConApp tc _)   = isUnLiftedTyCon tc
isStrictType (NewTcApp tc tys) = isStrictType (newTypeRep tc tys)
isStrictType (PredTy pred)     = isStrictPred pred
isStrictType other	       = False	

isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
isStrictPred other	     = False
831
832
833
834
835
836
837
838
839
840
841
842
	-- 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
843
			Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
844
845
846
847
					      isPrimTyCon tc
			other		   -> False
\end{code}

848

849
850
851
852
853
854
855
856
857
858
859
860
%************************************************************************
%*									*
\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
861
seqType (PredTy p) 	  = seqPred p
862
seqType (TyConApp tc tys) = tc `seq` seqTypes tys
863
seqType (NewTcApp tc tys) = tc `seq` seqTypes tys
864
865
866
867
868
869
870
871
872
seqType (ForAllTy tv ty)  = tv `seq` seqType ty

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

seqNote :: TyNote -> ()
seqNote (SynNote ty)  = seqType ty
seqNote (FTVNote set) = sizeUniqSet set `seq` ()
873

874
seqPred :: PredType -> ()
875
876
seqPred (ClassP c tys) = c  `seq` seqTypes tys
seqPred (IParam n ty)  = n  `seq` seqType ty
877
878
879
880
881
882
883
884
885
\end{code}


%************************************************************************
%*									*
\subsection{Equality on types}
%*									*
%************************************************************************

886
887
Comparison; don't use instances so that we know where it happens.
Look through newtypes but not usage types.
888

889
890
891
892
893
894
895
896
897
898
Note that eqType can respond 'False' for partial applications of newtypes.
Consider
	newtype Parser m a = MkParser (Foogle m a)

Does 	
	Monad (Parser m) `eqType` Monad (Foogle m)

Well, yes, but eqType won't see that they are the same. 
I don't think this is harmful, but it's soemthing to watch out for.

899
\begin{code}
900
901
902
903
904
905
906
eqType t1 t2 = eq_ty emptyVarEnv t1 t2
eqKind  = eqType	-- No worries about looking 

-- Look through Notes
eq_ty env (NoteTy _ t1)       t2	  	  = eq_ty env t1 t2
eq_ty env t1		      (NoteTy _ t2)       = eq_ty env t1 t2

907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
-- Look through PredTy and NewTcApp.  This is where the looping danger comes from.
-- We don't bother to check for the PredType/PredType case, no good reason
-- Hmm: maybe there is a good reason: see the notes below about newtypes
eq_ty env (PredTy sty1)     t2		  = eq_ty env (predTypeRep sty1) t2
eq_ty env t1		    (PredTy sty2) = eq_ty env t1 (predTypeRep sty2)

-- NB: we *cannot* short-cut the newtype comparison thus:
-- eq_ty env (NewTcApp tc1 tys1) (NewTcApp tc2 tys2) 
--	| (tc1 == tc2) = (eq_tys env tys1 tys2)
--
-- Consider:
--	newtype T a = MkT [a]
--	newtype Foo m = MkFoo (forall a. m a -> Int)
--	w1 :: Foo []
--	w1 = ...
--	
--	w2 :: Foo T
--	w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
--
-- We end up with w2 = w1; so we need that Foo T = Foo []
-- but we can only expand saturated newtypes, so just comparing
-- T with [] won't do. 

eq_ty env (NewTcApp tc1 tys1) t2		  = eq_ty env (newTypeRep tc1 tys1) t2
eq_ty env t1		      (NewTcApp tc2 tys2) = eq_ty env t1 (newTypeRep tc2 tys2)
932
933
934
935
936
937

-- The rest is plain sailing
eq_ty env (TyVarTy tv1)       (TyVarTy tv2)       = case lookupVarEnv env tv1 of
							  Just tv1a -> tv1a == tv2
							  Nothing   -> tv1  == tv2
eq_ty env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   
938
	| tv1 == tv2				  = eq_ty (delVarEnv env tv1)        t1 t2
939
940
941
942
943
944
945
	| otherwise				  = eq_ty (extendVarEnv env tv1 tv2) t1 t2
eq_ty env (AppTy s1 t1)       (AppTy s2 t2)       = (eq_ty env s1 s2) && (eq_ty env t1 t2)
eq_ty env (FunTy s1 t1)       (FunTy s2 t2)       = (eq_ty env s1 s2) && (eq_ty env t1 t2)
eq_ty env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 == tc2) && (eq_tys env tys1 tys2)
eq_ty env t1		       t2		  = False

eq_tys env []        []        = True
apt's avatar
apt committed
946
eq_tys env (t1:tys1) (t2:tys2) = (eq_ty env t1 t2) && (eq_tys env tys1 tys2)
947
eq_tys env tys1      tys2      = False
948
949
\end{code}