Type.lhs 29.5 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
	Type, PredType, ThetaType,
10
	Kind, TyVarSubst, 
11

12
13
	TyThing(..), isTyClThing,

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

23
24
25
26
27
        usageKindCon,					-- :: KX
        usageTypeKind,					-- :: KX
        usOnceTyCon, usManyTyCon,			-- :: $
        usOnce, usMany,					-- :: $

28
        -- exports from this module:
29
        hasMoreBoxityInfo, defaultKind,
30

31
32
	mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,

33
	mkAppTy, mkAppTys, splitAppTy, splitAppTys, splitAppTy_maybe,
34

35
	mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, splitFunTys, 
36
	funResultTy, funArgTy, zipFunTys, isFunTy,
37

38
	mkGenTyConApp, mkTyConApp, mkTyConTy, 
39
40
	tyConAppTyCon, tyConAppArgs, 
	splitTyConApp_maybe, splitTyConApp,
41

42
	mkSynTy, 
43

44
	repType, typePrimRep,
45

46
	mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, 
47
	applyTy, applyTys, isForAllTy, dropForAlls,
48

49
	-- Source types
50
	SourceType(..), sourceTypeRep, mkPredTy, mkPredTys,
51

52
	-- Newtypes
53
	splitNewType_maybe,
54

55
	-- Lifting and boxity
56
	isUnLiftedType, isUnboxedTupleType, isAlgType, isStrictType, isPrimitiveType,
57

58
	-- Free variables
59
	tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
60
	typeKind, addFreeTyVars,
61

62
	-- Tidying up for printing
63
64
65
66
67
	tidyType,      tidyTypes,
	tidyOpenType,  tidyOpenTypes,
	tidyTyVarBndr, tidyFreeTyVars,
	tidyOpenTyVar, tidyOpenTyVars,
	tidyTopType,   tidyPred,
68

69
70
71
	-- Comparison
	eqType, eqKind, eqUsage, 

72
73
74
	-- Seq
	seqType, seqTypes

75
    ) where
76

77
78
#include "HsVersions.h"

79
80
81
82
83
84
85
-- We import the representation and primitive functions from TypeRep.
-- Many things are reexported, but not the representation!

import TypeRep

-- Other imports:

86
import {-# SOURCE #-}	PprType( pprType )	-- Only called in debug messages
87
import {-# SOURCE #-}   Subst  ( substTyWith )
88
89

-- friends:
90
import Var	( Id, TyVar, tyVarKind, tyVarName, setTyVarName )
91
92
93
import VarEnv
import VarSet

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

104
-- others
105
import CmdLineOpts	( opt_DictsStrict )
106
import SrcLoc		( noSrcLoc )
107
import PrimRep		( PrimRep(..) )
108
import Unique		( Uniquable(..) )
sof's avatar
sof committed
109
import Util		( mapAccumL, seqList, lengthIs )
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
131
132
133
134
135
136
137
138
%************************************************************************
%*									*
			TyThing
%*									*
%************************************************************************

\begin{code}
data TyThing = AnId   Id
	     | ATyCon TyCon
	     | AClass Class

isTyClThing :: TyThing -> Bool
isTyClThing (ATyCon _) = True
isTyClThing (AClass _) = True
isTyClThing (AnId   _) = False

instance NamedThing TyThing where
  getName (AnId id)   = getName id
  getName (ATyCon tc) = getName tc
  getName (AClass cl) = getName cl
\end{code}


139
140
%************************************************************************
%*									*
141
\subsection{Stuff to do with kinds.}
142
143
144
145
%*									*
%************************************************************************

\begin{code}
146
hasMoreBoxityInfo :: Kind -> Kind -> Bool
147
-- (k1 `hasMoreBoxityInfo` k2) checks that k1 <: k2
148
hasMoreBoxityInfo k1 k2
149
  | k2 `eqKind` openTypeKind = isAnyTypeKind k1
150
151
  | otherwise	  	     = k1 `eqKind` k2
  where
152
153
154
155
156
157

isAnyTypeKind :: Kind -> Bool
-- True of kind * and *# and ?
isAnyTypeKind (TyConApp tc _) = tc == typeCon || tc == openKindCon
isAnyTypeKind (NoteTy _ k)    = isAnyTypeKind k
isAnyTypeKind other	      = False
158
159
160
161
162
163

isTypeKind :: Kind -> Bool
-- True of kind * and *#
isTypeKind (TyConApp tc _) = tc == typeCon
isTypeKind (NoteTy _ k)    = isTypeKind k
isTypeKind other	   = False
164
165
166

defaultKind :: Kind -> Kind
-- Used when generalising: default kind '?' to '*'
167
168
defaultKind kind | kind `eqKind` openTypeKind = liftedTypeKind
	         | otherwise	 	      = kind
169
\end{code}
170
171


172
173
174
175
176
%************************************************************************
%*									*
\subsection{Constructor-specific functions}
%*									*
%************************************************************************
sof's avatar
sof committed
177
178


179
180
181
---------------------------------------------------------------------
				TyVarTy
				~~~~~~~
182
\begin{code}
183
mkTyVarTy  :: TyVar   -> Type
184
mkTyVarTy  = TyVarTy
185

186
mkTyVarTys :: [TyVar] -> [Type]
187
mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
188

189
getTyVar :: String -> Type -> TyVar
190
191
192
193
getTyVar msg (TyVarTy tv)     = tv
getTyVar msg (SourceTy p)     = getTyVar msg (sourceTypeRep p)
getTyVar msg (NoteTy _ t)     = getTyVar msg t
getTyVar msg other	      = panic ("getTyVar: " ++ msg)
194

195
getTyVar_maybe :: Type -> Maybe TyVar
196
197
198
199
getTyVar_maybe (TyVarTy tv) 	= Just tv
getTyVar_maybe (NoteTy _ t) 	= getTyVar_maybe t
getTyVar_maybe (SourceTy p) 	= getTyVar_maybe (sourceTypeRep p)
getTyVar_maybe other	        = Nothing
200

201
isTyVarTy :: Type -> Bool
202
203
204
205
isTyVarTy (TyVarTy tv)     = True
isTyVarTy (NoteTy _ ty)    = isTyVarTy ty
isTyVarTy (SourceTy p)     = isTyVarTy (sourceTypeRep p)
isTyVarTy other            = False
206
207
208
\end{code}


209
210
211
212
213
214
---------------------------------------------------------------------
				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.
215

216
\begin{code}
217
mkAppTy orig_ty1 orig_ty2
218
  = ASSERT( not (isSourceTy orig_ty1) )	-- Source types are of kind *
219
    mk_app orig_ty1
220
  where
221
    mk_app (NoteTy _ ty1)    = mk_app ty1
222
    mk_app (TyConApp tc tys) = mkGenTyConApp tc (tys ++ [orig_ty2])
223
    mk_app ty1		     = AppTy orig_ty1 orig_ty2
224
225
226
227
228
229
230
231
	-- 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
232

233
mkAppTys :: Type -> [Type] -> Type
234
235
mkAppTys orig_ty1 []	    = orig_ty1
	-- This check for an empty list of type arguments
236
	-- avoids the needless loss of a type synonym constructor.
237
238
239
	-- For example: mkAppTys Rational []
	--   returns to (Ratio Integer), which has needlessly lost
	--   the Rational part.
240
mkAppTys orig_ty1 orig_tys2
241
  = ASSERT( not (isSourceTy orig_ty1) )	-- Source types are of kind *
242
    mk_app orig_ty1
243
  where
244
    mk_app (NoteTy _ ty1)    = mk_app ty1
245
    mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
246
    mk_app ty1		     = foldl AppTy orig_ty1 orig_tys2
247

248
splitAppTy_maybe :: Type -> Maybe (Type, Type)
249
splitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
250
251
splitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
splitAppTy_maybe (NoteTy _ ty)     = splitAppTy_maybe ty
252
splitAppTy_maybe (SourceTy p)        = splitAppTy_maybe (sourceTypeRep p)
253
254
splitAppTy_maybe (TyConApp tc [])  = Nothing
splitAppTy_maybe (TyConApp tc tys) = split tys []
255
			    where
256
			       split [ty2]    acc = Just (TyConApp tc (reverse acc), ty2)
257
			       split (ty:tys) acc = split tys (ty:acc)
258
259
260

splitAppTy_maybe other	     	  = Nothing

261
splitAppTy :: Type -> (Type, Type)
262
263
264
splitAppTy ty = case splitAppTy_maybe ty of
			Just pr -> pr
			Nothing -> panic "splitAppTy"
265

266
splitAppTys :: Type -> (Type, [Type])
267
splitAppTys ty = split ty ty []
268
  where
269
    split orig_ty (AppTy ty arg)        args = split ty ty (arg:args)
270
    split orig_ty (NoteTy _ ty)         args = split orig_ty ty args
271
    split orig_ty (SourceTy p)            args = split orig_ty (sourceTypeRep p) args
272
    split orig_ty (FunTy ty1 ty2)       args = ASSERT( null args )
273
					       (TyConApp funTyCon [], [ty1,ty2])
274
275
    split orig_ty (TyConApp tc tc_args) args = (TyConApp tc [], tc_args ++ args)
    split orig_ty ty		        args = (orig_ty, args)
276
277
\end{code}

278
279
280
281
282

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

283
\begin{code}
284
mkFunTy :: Type -> Type -> Type
285
mkFunTy arg res = FunTy arg res
286

287
mkFunTys :: [Type] -> Type -> Type
288
mkFunTys tys ty = foldr FunTy ty tys
289

290
291
292
isFunTy :: Type -> Bool 
isFunTy ty = isJust (splitFunTy_maybe ty)

293
294
295
splitFunTy :: Type -> (Type, Type)
splitFunTy (FunTy arg res) = (arg, res)
splitFunTy (NoteTy _ ty)   = splitFunTy ty
296
splitFunTy (SourceTy p)    = splitFunTy (sourceTypeRep p)
297

298
splitFunTy_maybe :: Type -> Maybe (Type, Type)
299
300
splitFunTy_maybe (FunTy arg res) = Just (arg, res)
splitFunTy_maybe (NoteTy _ ty)   = splitFunTy_maybe ty
301
splitFunTy_maybe (SourceTy p)    = splitFunTy_maybe (sourceTypeRep p)
302
splitFunTy_maybe other	         = Nothing
303

304
splitFunTys :: Type -> ([Type], Type)
305
splitFunTys ty = split [] ty ty
306
  where
307
    split args orig_ty (FunTy arg res) = split (arg:args) res res
308
    split args orig_ty (NoteTy _ ty)   = split args orig_ty ty
309
    split args orig_ty (SourceTy p)    = split args orig_ty (sourceTypeRep p)
310
    split args orig_ty ty              = (reverse args, orig_ty)
311

312
313
314
315
316
317
zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
  where
    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
318
    split acc xs     nty (SourceTy p)    = split acc           xs nty (sourceTypeRep p)
319
320
321
    split acc (x:xs) nty ty              = pprPanic "zipFunTys" (ppr orig_xs <+> pprType orig_ty)
    
funResultTy :: Type -> Type
322
323
funResultTy (FunTy arg res) = res
funResultTy (NoteTy _ ty)   = funResultTy ty
324
funResultTy (SourceTy p)    = funResultTy (sourceTypeRep p)
325
funResultTy ty		    = pprPanic "funResultTy" (pprType ty)
326
327
328
329

funArgTy :: Type -> Type
funArgTy (FunTy arg res) = arg
funArgTy (NoteTy _ ty)   = funArgTy ty
330
funArgTy (SourceTy p)    = funArgTy (sourceTypeRep p)
331
funArgTy ty		 = pprPanic "funArgTy" (pprType ty)
332
333
334
\end{code}


335
336
337
---------------------------------------------------------------------
				TyConApp
				~~~~~~~~
338
339
@mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or SourceTy,
as apppropriate.
340

341
\begin{code}
342
343
344
345
346
mkGenTyConApp :: TyCon -> [Type] -> Type
mkGenTyConApp tc tys
  | isSynTyCon tc = mkSynTy tc tys
  | otherwise     = mkTyConApp tc tys

347
mkTyConApp :: TyCon -> [Type] -> Type
348
-- Assumes TyCon is not a SynTyCon; use mkSynTy instead for those
349
mkTyConApp tycon tys
350
  | isFunTyCon tycon, [ty1,ty2] <- tys
351
  = FunTy ty1 ty2
352
353
354

  | isNewTyCon tycon,			-- A saturated newtype application;
    not (isRecursiveTyCon tycon),	-- Not recursive (we don't use SourceTypes for them)
sof's avatar
sof committed
355
    tys `lengthIs` tyConArity tycon     -- use the SourceType form
356
  = SourceTy (NType tycon tys)
357
358
359
360
361

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

362
mkTyConTy :: TyCon -> Type
363
364
365
366
367
368
369
mkTyConTy tycon = ASSERT( not (isSynTyCon tycon) ) 
		  TyConApp tycon []

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

370
tyConAppTyCon :: Type -> TyCon
371
tyConAppTyCon ty = fst (splitTyConApp ty)
372
373

tyConAppArgs :: Type -> [Type]
374
tyConAppArgs ty = snd (splitTyConApp ty)
375
376
377
378
379
380

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

381
splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
382
splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
383
splitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
384
splitTyConApp_maybe (NoteTy _ ty)     = splitTyConApp_maybe ty
385
splitTyConApp_maybe (SourceTy p)      = splitTyConApp_maybe (sourceTypeRep p)
386
splitTyConApp_maybe other	      = Nothing
sof's avatar
sof committed
387
\end{code}
388

389

390
391
392
393
---------------------------------------------------------------------
				SynTy
				~~~~~

394
\begin{code}
395
396
397
398
mkSynTy tycon tys
  | n_args == arity	-- Exactly saturated
  = mk_syn tys
  | n_args >  arity	-- Over-saturated
399
400
401
402
  = 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!
403
404
405
406
407
408
409
410
  | 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.

411
  where
412
413
414
415
416
417
    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
418
419
\end{code}

420
421
422
423
Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
to return type synonyms whereever possible. Thus
424

425
426
427
428
429
430
431
432
	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.
433
434


435
436
		Representation types
		~~~~~~~~~~~~~~~~~~~~
437
438
repType looks through 
	(a) for-alls, and
439
440
441
	(b) synonyms
	(c) predicates
	(d) usage annotations
442
	(e) [recursive] newtypes
443
It's useful in the back end.
444

445
446
447
448
Remember, non-recursive newtypes get expanded as part of the SourceTy case,
but recursive ones are represented by TyConApps and have to be expanded
by steam.

449
450
\begin{code}
repType :: Type -> Type
451
452
453
repType (ForAllTy _ ty)   = repType ty
repType (NoteTy   _ ty)   = repType ty
repType (SourceTy  p)     = repType (sourceTypeRep p)
sof's avatar
sof committed
454
repType (TyConApp tc tys) | isNewTyCon tc && tys `lengthIs` tyConArity tc
455
456
			  = repType (newTypeRep tc tys)
repType ty	 	  = ty
457

458
459
460
461
462
463
464

typePrimRep :: Type -> PrimRep
typePrimRep ty = case repType ty of
		   TyConApp tc _ -> tyConPrimRep tc
		   FunTy _ _	 -> PtrRep
		   AppTy _ _	 -> PtrRep	-- ??
		   TyVarTy _	 -> PtrRep
465
466
467
\end{code}


468

469
470
471
---------------------------------------------------------------------
				ForAllTy
				~~~~~~~~
472
473

\begin{code}
474
mkForAllTy :: TyVar -> Type -> Type
475
476
mkForAllTy tyvar ty
  = mkForAllTys [tyvar] ty
477

478
mkForAllTys :: [TyVar] -> Type -> Type
479
mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
480
481
482
483
484

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

486
splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
487
splitForAllTy_maybe ty = splitFAT_m ty
488
  where
489
    splitFAT_m (NoteTy _ ty)		= splitFAT_m ty
490
    splitFAT_m (SourceTy p)		= splitFAT_m (sourceTypeRep p)
491
492
    splitFAT_m (ForAllTy tyvar ty)	= Just(tyvar, ty)
    splitFAT_m _			= Nothing
sof's avatar
sof committed
493

494
splitForAllTys :: Type -> ([TyVar], Type)
495
splitForAllTys ty = split ty ty []
496
   where
497
498
     split orig_ty (ForAllTy tv ty)	  tvs = split ty ty (tv:tvs)
     split orig_ty (NoteTy _ ty)	  tvs = split orig_ty ty tvs
499
     split orig_ty (SourceTy p)		  tvs = split orig_ty (sourceTypeRep p) tvs
500
     split orig_ty t			  tvs = (reverse tvs, orig_ty)
501
502
503

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

506
-- (mkPiType now in CoreUtils)
507

508
Applying a for-all to its arguments.  Lift usage annotation as required.
509

510
\begin{code}
511
applyTy :: Type -> Type -> Type
512
513
514
515
applyTy (SourceTy p) 	 arg = applyTy (sourceTypeRep p) arg
applyTy (NoteTy _ fun)   arg = applyTy fun arg
applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
applyTy other		 arg = panic "applyTy"
516

517
applyTys :: Type -> [Type] -> Type
518
applyTys orig_fun_ty arg_tys
519
 = substTyWith tvs arg_tys ty
520
 where
521
   (tvs, ty) = split orig_fun_ty arg_tys
522
   
523
   split fun_ty               []         = ([], fun_ty)
524
   split (NoteTy _ fun_ty)    args       = split fun_ty args
525
   split (SourceTy p)	      args       = split (sourceTypeRep p) args
526
   split (ForAllTy tv fun_ty) (arg:args) = case split fun_ty args of
527
						  (tvs, ty) -> (tv:tvs, ty)
528
   split other_ty             args       = panic "applyTys"
529
	-- No show instance for Type yet
530
\end{code}
531

532

533
534
%************************************************************************
%*									*
535
\subsection{Source types}
536
537
%*									*
%************************************************************************
538

539
540
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.
541

542
Source types are always lifted.
543

544
The key function is sourceTypeRep which gives the representation of a source type:
545
546

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

mkPredTys :: ThetaType -> [Type]
mkPredTys preds = map SourceTy preds

553
554
555
sourceTypeRep :: SourceType -> Type
-- Convert a predicate to its "representation type";
-- the type of evidence for that predicate, which is actually passed at runtime
556
sourceTypeRep (IParam _ ty)     = ty
557
558
sourceTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
	-- Note the mkTyConApp; the classTyCon might be a newtype!
559
sourceTypeRep (NType  tc tys)   = newTypeRep tc tys
560
561
562
563
564
565
	-- ToDo: Consider caching this substitution in a NType

isSourceTy :: Type -> Bool
isSourceTy (NoteTy _ ty)  = isSourceTy ty
isSourceTy (SourceTy sty) = True
isSourceTy _	          = False
566
567
568
569
570
571
572
573
574


splitNewType_maybe :: Type -> Maybe Type
-- Newtypes that are recursive are reprsented by TyConApp, just
-- as they always were.  Occasionally we want to find their representation type.
-- NB: remember that in this module, non-recursive newtypes are transparent

splitNewType_maybe ty
  = case splitTyConApp_maybe ty of
sof's avatar
sof committed
575
	Just (tc,tys) | isNewTyCon tc -> ASSERT( tys `lengthIs` tyConArity tc )
576
577
578
579
580
581
582
583
						-- The assert should hold because repType should
						-- only be applied to *types* (of kind *)
					 Just (newTypeRep tc tys)
	other -> Nothing
			
-- A local helper function (not exported)
newTypeRep new_tycon tys = case newTyConRep new_tycon of
			     (tvs, rep_ty) -> substTyWith tvs tys rep_ty
584
585
\end{code}

586

587
588
589
590
591
592
593
594
595
%************************************************************************
%*									*
\subsection{Kinds and free variables}
%*									*
%************************************************************************

---------------------------------------------------------------------
		Finding the kind of a type
		~~~~~~~~~~~~~~~~~~~~~~~~~~
596
\begin{code}
597
typeKind :: Type -> Kind
598

599
typeKind (TyVarTy tyvar)	= tyVarKind tyvar
600
601
typeKind (TyConApp tycon tys)	= foldr (\_ k -> funResultTy k) (tyConKind tycon) tys
typeKind (NoteTy _ ty)		= typeKind ty
602
typeKind (SourceTy _)		= liftedTypeKind -- Predicates are always 
603
						 -- represented by lifted types
604
typeKind (AppTy fun arg)	= funResultTy (typeKind fun)
605

606
607
typeKind (FunTy arg res)	= fix_up (typeKind res)
				where
608
				  fix_up (TyConApp tycon _) |  tycon == typeCon
609
							    || tycon == openKindCon = liftedTypeKind
610
611
				  fix_up (NoteTy _ kind) = fix_up kind
				  fix_up kind	         = kind
612
613
		-- The basic story is 
		-- 	typeKind (FunTy arg res) = typeKind res
614
		-- But a function is lifted regardless of its result type
615
616
617
		-- Hence the strange fix-up.
		-- Note that 'res', being the result of a FunTy, can't have 
		-- a strange kind like (*->*).
618
619

typeKind (ForAllTy tv ty)	= typeKind ty
620
621
622
\end{code}


623
624
625
---------------------------------------------------------------------
		Free variables of a type
		~~~~~~~~~~~~~~~~~~~~~~~~
626
\begin{code}
627
tyVarsOfType :: Type -> TyVarSet
628
tyVarsOfType (TyVarTy tv)		= unitVarSet tv
629
tyVarsOfType (TyConApp tycon tys)	= tyVarsOfTypes tys
630
tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
631
tyVarsOfType (NoteTy (SynNote ty1) ty2)	= tyVarsOfType ty2	-- See note [Syn] below
632
tyVarsOfType (SourceTy sty)		= tyVarsOfSourceType sty
633
634
635
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
636

637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
-- 			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.


652
tyVarsOfTypes :: [Type] -> TyVarSet
653
654
tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys

655
tyVarsOfPred :: PredType -> TyVarSet
656
657
658
tyVarsOfPred = tyVarsOfSourceType	-- Just a subtype

tyVarsOfSourceType :: SourceType -> TyVarSet
659
660
661
tyVarsOfSourceType (IParam _ ty)  = tyVarsOfType ty
tyVarsOfSourceType (ClassP _ tys) = tyVarsOfTypes tys
tyVarsOfSourceType (NType _ tys)  = tyVarsOfTypes tys
662
663

tyVarsOfTheta :: ThetaType -> TyVarSet
664
tyVarsOfTheta = foldr (unionVarSet . tyVarsOfSourceType) emptyVarSet
665

666
-- Add a Note with the free tyvars to the top of the type
667
addFreeTyVars :: Type -> Type
668
669
addFreeTyVars ty@(NoteTy (FTVNote _) _)      = ty
addFreeTyVars ty			     = NoteTy (FTVNote (tyVarsOfType ty)) ty
670
\end{code}
671

672
673
674
675
676
%************************************************************************
%*									*
\subsection{TidyType}
%*									*
%************************************************************************
677

678
679
tidyTy tidies up a type for printing in an error message, or in
an interface file.
680

681
It doesn't change the uniques at all, just the print names.
682
683

\begin{code}
684
685
686
687
688
689
690
691
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'
692
			name'  = mkInternalName (getUnique name) occ' noSrcLoc
693
694
				-- Note: make a *user* tyvar, so it printes nicely
				-- Could extract src loc, but no need.
695
696
  where
    name = tyVarName tyvar
697

698
699
700
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
701
702
703
704
705
706
707
708
709
710
711
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
712

713
714
715
tidyType :: TidyEnv -> Type -> Type
tidyType env@(tidy_env, subst) ty
  = go ty
716
  where
717
718
719
    go (TyVarTy tv)	    = case lookupVarEnv subst tv of
				Nothing  -> TyVarTy tv
				Just tv' -> TyVarTy tv'
720
721
    go (TyConApp tycon tys) = let args = map go tys
			      in args `seqList` TyConApp tycon args
sof's avatar
sof committed
722
    go (NoteTy note ty)     = (NoteTy $! (go_note note)) $! (go ty)
723
    go (SourceTy sty)	    = SourceTy (tidySourceType env sty)
sof's avatar
sof committed
724
725
726
    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)
727
			      where
728
			        (envp, tvp) = tidyTyVarBndr env tv
729

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

733
tidyTypes env tys = map (tidyType env) tys
734

735
736
737
738
739
740
741
tidyPred :: TidyEnv -> SourceType -> SourceType
tidyPred = tidySourceType

tidySourceType :: TidyEnv -> SourceType -> SourceType
tidySourceType env (IParam n ty)     = IParam n (tidyType env ty)
tidySourceType env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
tidySourceType env (NType tc tys)    = NType  tc   (tidyTypes env tys)
742
743
744
\end{code}


745
@tidyOpenType@ grabs the free type variables, tidies them
746
747
748
749
750
751
752
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
753
    env' = tidyFreeTyVars env (tyVarsOfType ty)
754
755
756
757
758
759

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

tidyTopType :: Type -> Type
tidyTopType ty = tidyType emptyTidyEnv ty
760
761
\end{code}

762

763

764
765
%************************************************************************
%*									*
766
\subsection{Liftedness}
767
768
769
%*									*
%************************************************************************

770
\begin{code}
771
isUnLiftedType :: Type -> Bool
772
773
774
775
776
777
778
779
780
	-- 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

isUnLiftedType (ForAllTy tv ty) = isUnLiftedType ty
isUnLiftedType (NoteTy _ ty)	= isUnLiftedType ty
isUnLiftedType (TyConApp tc _)  = isUnLiftedTyCon tc
781
782
isUnLiftedType (SourceTy _)	= False		-- All source types are lifted
isUnLiftedType other		= False	
783

784
isUnboxedTupleType :: Type -> Bool
785
786
787
isUnboxedTupleType ty = case splitTyConApp_maybe ty of
			   Just (tc, ty_args) -> isUnboxedTupleTyCon tc
			   other	      -> False
788

789
-- Should only be applied to *types*; hence the assert
790
isAlgType :: Type -> Bool
791
isAlgType ty = case splitTyConApp_maybe ty of
sof's avatar
sof committed
792
			Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
793
794
					      isAlgTyCon tc
			other		   -> False
795
796
\end{code}

797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
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}
isStrictType (ForAllTy tv ty)		= isStrictType ty
isStrictType (NoteTy _ ty)   		= isStrictType ty
isStrictType (TyConApp tc _)		= isUnLiftedTyCon tc
isStrictType (SourceTy (ClassP clas _)) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
	-- 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.]
isStrictType other			= False	
\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
822
			Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
823
824
825
826
					      isPrimTyCon tc
			other		   -> False
\end{code}

827

828
829
830
831
832
833
834
835
836
837
838
839
%************************************************************************
%*									*
\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
840
seqType (SourceTy p) 	  = seqPred p
841
842
843
844
845
846
847
848
849
850
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 (SynNote ty)  = seqType ty
seqNote (FTVNote set) = sizeUniqSet set `seq` ()
851

852
853
854
855
seqPred :: SourceType -> ()
seqPred (ClassP c tys) = c  `seq` seqTypes tys
seqPred (NType tc tys) = tc `seq` seqTypes tys
seqPred (IParam n ty)  = n  `seq` seqType ty
856
857
858
859
860
861
862
863
864
\end{code}


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

865
866
Comparison; don't use instances so that we know where it happens.
Look through newtypes but not usage types.
867

868
869
870
871
872
873
874
875
876
877
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.

878
\begin{code}
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
eqType t1 t2 = eq_ty emptyVarEnv t1 t2
eqKind  = eqType	-- No worries about looking 
eqUsage = eqType	-- through source types for these two

-- 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

-- Look through SourceTy.  This is where the looping danger comes from
eq_ty env (SourceTy sty1)     t2		  = eq_ty env (sourceTypeRep sty1) t2
eq_ty env t1		      (SourceTy sty2)     = eq_ty env t1 (sourceTypeRep sty2)

-- 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)   
896
	| tv1 == tv2				  = eq_ty (delVarEnv env tv1)        t1 t2
897
898
899
900
901
902
903
	| 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
904
eq_tys env (t1:tys1) (t2:tys2) = (eq_ty env t1 t2) && (eq_tys env tys1 tys2)
905
eq_tys env tys1      tys2      = False
906
907
\end{code}