TcType.lhs 40.1 KB
Newer Older
1
2
3
4
5
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[TcType]{Types used in the typechecker}

6
7
This module provides the Type interface for front-end parts of the 
compiler.  These parts 
8

9
10
11
	* treat "source types" as opaque: 
		newtypes, and predicates are meaningful. 
	* look through usage types
12

13
14
The "tc" prefix is for "typechechecker", because the type checker
is the principal client.
15

16
17
\begin{code}
module TcType (
18
  --------------------------------
19
  -- Types 
20
  TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType, 
21
  TcTyVar, TcTyVarSet, TcKind, 
22
23
24

  --------------------------------
  -- TyVarDetails
25
  TyVarDetails(..), isUserTyVar, isSkolemTyVar, 
26
  tyVarBindingInfo,
27
28

  --------------------------------
29
  -- Builders
30
  mkPhiTy, mkSigmaTy, 
31

32
33
34
  --------------------------------
  -- Splitters  
  -- These are important because they do not look through newtypes
35
  tcSplitForAllTys, tcSplitPhiTy, 
36
37
  tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy,
  tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
38
  tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, tcSplitSigmaTy,
39
40
41
42
43
  tcSplitMethodTy, tcGetTyVar_maybe, tcGetTyVar,

  ---------------------------------
  -- Predicates. 
  -- Again, newtypes are opaque
44
  tcEqType, tcEqTypes, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred,
45
  isSigmaTy, isOverloadedTy, 
46
  isDoubleTy, isFloatTy, isIntTy,
47
  isIntegerTy, isAddrTy, isBoolTy, isUnitTy,
48
  isTauTy, tcIsTyVarTy, tcIsForAllTy,
49
  allDistinctTyVars,
50
51
52

  ---------------------------------
  -- Misc type manipulators
53
  deNoteType, classesOfTheta,
54
  tyClsNamesOfType, tyClsNamesOfDFunHead, 
55
56
57
58
  getDFunTyKey,

  ---------------------------------
  -- Predicate types  
59
  getClassPredTys_maybe, getClassPredTys, 
60
  isClassPred, isTyVarClassPred, 
61
  mkDictTy, tcSplitPredTy_maybe, 
62
  isPredTy, isDictTy, tcSplitDFunTy, predTyUnique, 
63
  mkClassPred, isInheritablePred, isLinearPred, isIPPred, mkPredName, 
64

65
66
67
68
69
70
71
72
73
  ---------------------------------
  -- Foreign import and export
  isFFIArgumentTy,     -- :: DynFlags -> Safety -> Type -> Bool
  isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
  isFFIExportResultTy, -- :: Type -> Bool
  isFFIExternalTy,     -- :: Type -> Bool
  isFFIDynArgumentTy,  -- :: Type -> Bool
  isFFIDynResultTy,    -- :: Type -> Bool
  isFFILabelTy,        -- :: Type -> Bool
sof's avatar
sof committed
74
75
  isFFIDotnetTy,       -- :: DynFlags -> Type -> Bool
  isFFIDotnetObjTy,    -- :: Type -> Bool
76
  isFFITy,	       -- :: Type -> Bool
sof's avatar
sof committed
77
78
  
  toDNType,            -- :: Type -> DNType
79

80
81
82
83
  ---------------------------------
  -- Unifier and matcher  
  unifyTysX, unifyTyListsX, unifyExtendTysX,
  matchTy, matchTys, match,
84

85
86
  --------------------------------
  -- Rexported from Type
87
88
  Kind, 	-- Stuff to do with kinds is insensitive to pre/post Tc
  unliftedTypeKind, liftedTypeKind, openTypeKind, mkArrowKind, mkArrowKinds, 
89
  isLiftedTypeKind, isUnliftedTypeKind, isOpenTypeKind, 
90
  isArgTypeKind, isSubKind, defaultKind, 
91

92
  Type, PredType(..), ThetaType, 
93
94
  mkForAllTy, mkForAllTys, 
  mkFunTy, mkFunTys, zipFunTys, 
95
  mkTyConApp, mkGenTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
96
  mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys, 
97

98
99
  isUnLiftedType,	-- Source types are always lifted
  isUnboxedTupleType,	-- Ditto
100
  isPrimitiveType, 
101

102
  tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
103
  tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars,
104
  typeKind, 
105

106
  tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
107

108
109
110
  pprKind, pprParendKind,
  pprType, pprParendType,
  pprPred, pprTheta, pprThetaArrow, pprClassPred
111

112
  ) where
113

114
#include "HsVersions.h"
115

116
-- friends:
117
118
119
import TypeRep		( Type(..), TyNote(..), funTyCon )  -- friend

import Type		(	-- Re-exports
120
			  tyVarsOfType, tyVarsOfTypes, tyVarsOfPred,
121
			  tyVarsOfTheta, Kind, Type, PredType(..),
122
			  ThetaType, unliftedTypeKind, 
123
			  liftedTypeKind, openTypeKind, mkArrowKind,
124
		  	  isLiftedTypeKind, isUnliftedTypeKind, 
125
			  isOpenTypeKind, 
126
			  mkArrowKinds, mkForAllTy, mkForAllTys,
127
			  defaultKind, isArgTypeKind, isOpenTypeKind,
128
			  mkFunTy, mkFunTys, zipFunTys, 
129
130
131
			  mkTyConApp, mkGenTyConApp, mkAppTy,
			  mkAppTys, mkSynTy, applyTy, applyTys,
			  mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy,
132
			  mkPredTys, isUnLiftedType, 
133
			  isUnboxedTupleType, isPrimitiveType,
134
			  splitTyConApp_maybe,
135
136
137
			  tidyTopType, tidyType, tidyPred, tidyTypes,
			  tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
			  tidyTyVarBndr, tidyOpenTyVar,
138
139
140
			  tidyOpenTyVars, 
			  isSubKind, 
			  typeKind, repType,
141
142
143
			  pprKind, pprParendKind,
			  pprType, pprParendType,
			  pprPred, pprTheta, pprThetaArrow, pprClassPred
144
			)
145
import TyCon		( TyCon, isUnLiftedTyCon, tyConUnique )
146
import Class		( Class )
147
148
import Var		( TyVar, tyVarKind, tcTyVarDetails )
import ForeignCall	( Safety, playSafe, DNType(..) )
149
150
import VarEnv
import VarSet
151
152

-- others:
153
import CmdLineOpts	( DynFlags, DynFlag( Opt_GlasgowExts ), dopt )
154
import Name		( Name, NamedThing(..), mkInternalName, getSrcLoc )
155
import NameSet
156
import OccName		( OccName, mkDictOcc )
157
import PrelNames	-- Lots (e.g. in isFFIArgumentTy)
158
import TysWiredIn	( unitTyCon, charTyCon, listTyCon )
159
import BasicTypes	( IPName(..), ipNameName )
160
import Unique		( Unique, Uniquable(..) )
161
import SrcLoc		( SrcLoc )
162
import Util		( cmpList, thenCmp, equalLength, snocView )
163
import Maybes		( maybeToBool, expectJust )
164
import Outputable
165
166
167
\end{code}


168
169
%************************************************************************
%*									*
170
171
172
173
\subsection{Types}
%*									*
%************************************************************************

174
175
176
The type checker divides the generic Type world into the 
following more structured beasts:

177
sigma ::= forall tyvars. phi
178
179
180
181
182
183
184
185
186
187
	-- A sigma type is a qualified type
	--
	-- Note that even if 'tyvars' is empty, theta
	-- may not be: e.g.   (?x::Int) => Int

	-- Note that 'sigma' is in prenex form:
	-- all the foralls are at the front.
	-- A 'phi' type has no foralls to the right of
	-- an arrow

188
189
190
phi :: theta => rho

rho ::= sigma -> rho
191
192
193
194
195
196
197
198
199
200
201
202
     |  tau

-- A 'tau' type has no quantification anywhere
-- Note that the args of a type constructor must be taus
tau ::= tyvar
     |  tycon tau_1 .. tau_n
     |  tau_1 tau_2
     |  tau_1 -> tau_2

-- In all cases, a (saturated) type synonym application is legal,
-- provided it expands to the required form.

203
204
205
206
207
208
209
210
211
\begin{code}
type TcType = Type 		-- A TcType can have mutable type variables
	-- Invariant on ForAllTy in TcTypes:
	-- 	forall a. T
	-- a cannot occur inside a MutTyVar in T; that is,
	-- T is "flattened" before quantifying over a

type TcPredType     = PredType
type TcThetaType    = ThetaType
212
type TcSigmaType    = TcType
213
type TcRhoType      = TcType
214
type TcTauType      = TcType
215
216

type TcKind         = Kind
217
218
219
220
221
222
\end{code}


%************************************************************************
%*									*
\subsection{TyVarDetails}
223
224
225
%*									*
%************************************************************************

226
227
TyVarDetails gives extra info about type variables, used during type
checking.  It's attached to mutable type variables only.
228
229
It's knot-tied back to Var.lhs.  There is no reason in principle
why Var.lhs shouldn't actually have the definition, but it "belongs" here.
230

231
\begin{code}
232
233
type TcTyVar = TyVar  	-- Used only during type inference

234
data TyVarDetails
235
  = SigTv	-- Introduced when instantiating a type signature,
236
237
238
239
240
241
242
243
244
245
246
247
		-- prior to checking that the defn of a fn does 
		-- have the expected type.  Should not be instantiated.
		-- 	f :: forall a. a -> a
		-- 	f = e
		-- When checking e, with expected type (a->a), we 
		-- should not instantiate a

   | ClsTv	-- Scoped type variable introduced by a class decl
		--	class C a where ...

   | InstTv	-- Ditto, but instance decl

248
   | PatSigTv	-- Scoped type variable, introduced by a pattern
249
		-- type signature	\ x::a -> e
250

251
252
   | VanillaTv	-- Everything else

253
isUserTyVar :: TcTyVar -> Bool	-- Avoid unifying these if possible
254
isUserTyVar tv = case tcTyVarDetails tv of
255
256
257
258
		   VanillaTv -> False
		   other     -> True

isSkolemTyVar :: TcTyVar -> Bool
259
isSkolemTyVar tv = case tcTyVarDetails tv of
260
261
262
		      SigTv  -> True
		      ClsTv  -> True
		      InstTv -> True
263
264
		      oteher -> False

265
tyVarBindingInfo :: TcTyVar -> SDoc	-- Used in checkSigTyVars
266
tyVarBindingInfo tv
267
  = sep [ptext SLIT("is bound by the") <+> details (tcTyVarDetails tv),
268
269
270
271
272
	 ptext SLIT("at") <+> ppr (getSrcLoc tv)]
  where
    details SigTv     = ptext SLIT("type signature")
    details ClsTv     = ptext SLIT("class declaration")
    details InstTv    = ptext SLIT("instance declaration")
273
    details PatSigTv  = ptext SLIT("pattern type signature")
274
    details VanillaTv = ptext SLIT("//vanilla//")	-- Ditto
275
\end{code}
276

277
278
279
\begin{code}
type TcTyVarSet = TyVarSet
\end{code}
280
281
282
283
284
285
286
287

%************************************************************************
%*									*
\subsection{Tau, sigma and rho}
%*									*
%************************************************************************

\begin{code}
288
mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
sof's avatar
sof committed
289

290
mkPhiTy :: [PredType] -> Type -> Type
291
mkPhiTy theta ty = foldr (\p r -> FunTy (mkPredTy p) r) ty theta
292
293
294
\end{code}

@isTauTy@ tests for nested for-alls.
sof's avatar
sof committed
295

296
\begin{code}
297
298
299
isTauTy :: Type -> Bool
isTauTy (TyVarTy v)	 = True
isTauTy (TyConApp _ tys) = all isTauTy tys
300
isTauTy (NewTcApp _ tys) = all isTauTy tys
301
302
isTauTy (AppTy a b)	 = isTauTy a && isTauTy b
isTauTy (FunTy a b)	 = isTauTy a && isTauTy b
303
isTauTy (PredTy p)	 = True		-- Don't look through source types
304
305
306
307
308
309
310
isTauTy (NoteTy _ ty)	 = isTauTy ty
isTauTy other		 = False
\end{code}

\begin{code}
getDFunTyKey :: Type -> OccName	-- Get some string from a type, to be used to 
				-- construct a dictionary function name
311
312
313
314
315
316
317
318
319
getDFunTyKey (TyVarTy tv)    = getOccName tv
getDFunTyKey (TyConApp tc _) = getOccName tc
getDFunTyKey (NewTcApp tc _) = getOccName tc
getDFunTyKey (AppTy fun _)   = getDFunTyKey fun
getDFunTyKey (NoteTy _ t)    = getDFunTyKey t
getDFunTyKey (FunTy arg _)   = getOccName funTyCon
getDFunTyKey (ForAllTy _ t)  = getDFunTyKey t
getDFunTyKey ty		     = pprPanic "getDFunTyKey" (pprType ty)
-- PredTy shouldn't happen
sof's avatar
sof committed
320
321
322
\end{code}


323
324
%************************************************************************
%*									*
325
\subsection{Expanding and splitting}
326
327
%*									*
%************************************************************************
328

329
330
331
332
333
334
335
336
These tcSplit functions are like their non-Tc analogues, but
	a) they do not look through newtypes
	b) they do not look through PredTys
	c) [future] they ignore usage-type annotations

However, they are non-monadic and do not follow through mutable type
variables.  It's up to you to make sure this doesn't matter.

337
\begin{code}
338
339
340
341
342
343
344
345
346
347
348
tcSplitForAllTys :: Type -> ([TyVar], Type)
tcSplitForAllTys ty = split ty ty []
   where
     split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
     split orig_ty (NoteTy n  ty)   tvs = split orig_ty ty tvs
     split orig_ty t		    tvs = (reverse tvs, orig_ty)

tcIsForAllTy (ForAllTy tv ty) = True
tcIsForAllTy (NoteTy n ty)    = tcIsForAllTy ty
tcIsForAllTy t		      = False

349
350
tcSplitPhiTy :: Type -> ([PredType], Type)
tcSplitPhiTy ty = split ty ty []
351
352
353
354
355
356
357
358
 where
  split orig_ty (FunTy arg res) ts = case tcSplitPredTy_maybe arg of
					Just p  -> split res res (p:ts)
					Nothing -> (reverse ts, orig_ty)
  split orig_ty (NoteTy n ty)	ts = split orig_ty ty ts
  split orig_ty ty		ts = (reverse ts, orig_ty)

tcSplitSigmaTy ty = case tcSplitForAllTys ty of
359
			(tvs, rho) -> case tcSplitPhiTy rho of
360
361
362
363
364
365
366
367
368
369
370
371
372
373
					(theta, tau) -> (tvs, theta, tau)

tcTyConAppTyCon :: Type -> TyCon
tcTyConAppTyCon ty = fst (tcSplitTyConApp ty)

tcTyConAppArgs :: Type -> [Type]
tcTyConAppArgs ty = snd (tcSplitTyConApp ty)

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

tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
374
375
376
377
tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
tcSplitTyConApp_maybe (NewTcApp tc tys) = Just (tc, tys)
tcSplitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
tcSplitTyConApp_maybe (NoteTy n ty)     = tcSplitTyConApp_maybe ty
378
	-- Newtypes are opaque, so they may be split
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
	-- However, predicates are not treated
	-- as tycon applications by the type checker
tcSplitTyConApp_maybe other	        	= Nothing

tcSplitFunTys :: Type -> ([Type], Type)
tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
			Nothing	       -> ([], ty)
			Just (arg,res) -> (arg:args, res')
				       where
					  (args,res') = tcSplitFunTys res

tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
tcSplitFunTy_maybe (FunTy arg res)  = Just (arg, res)
tcSplitFunTy_maybe (NoteTy n ty)    = tcSplitFunTy_maybe ty
tcSplitFunTy_maybe other	    = Nothing

tcFunArgTy    ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> arg }
tcFunResultTy ty = case tcSplitFunTy_maybe ty of { Just (arg,res) -> res }


tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
400
401
402
403
404
405
406
407
408
409
tcSplitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
tcSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
tcSplitAppTy_maybe (NoteTy n ty)     = tcSplitAppTy_maybe ty
tcSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
					Just (tys', ty') -> Just (TyConApp tc tys', ty')
					Nothing		 -> Nothing
tcSplitAppTy_maybe (NewTcApp tc tys) = case snocView tys of
					Just (tys', ty') -> Just (NewTcApp tc tys', ty')
					Nothing		 -> Nothing
tcSplitAppTy_maybe other	     = Nothing
410
411
412
413
414

tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
		    Just stuff -> stuff
		    Nothing    -> pprPanic "tcSplitAppTy" (pprType ty)

415
416
417
418
419
420
421
422
tcSplitAppTys :: Type -> (Type, [Type])
tcSplitAppTys ty
  = go ty []
  where
    go ty args = case tcSplitAppTy_maybe ty of
		   Just (ty', arg) -> go ty' (arg:args)
		   Nothing	   -> (ty,args)

423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
tcGetTyVar_maybe :: Type -> Maybe TyVar
tcGetTyVar_maybe (TyVarTy tv) 	= Just tv
tcGetTyVar_maybe (NoteTy _ t) 	= tcGetTyVar_maybe t
tcGetTyVar_maybe other	        = Nothing

tcGetTyVar :: String -> Type -> TyVar
tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)

tcIsTyVarTy :: Type -> Bool
tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
\end{code}

The type of a method for class C is always of the form:
	Forall a1..an. C a1..an => sig_ty
where sig_ty is the type given by the method's signature, and thus in general
is a ForallTy.  At the point that splitMethodTy is called, it is expected
that the outer Forall has already been stripped off.  splitMethodTy then
440
returns (C a1..an, sig_ty') where sig_ty' is sig_ty with any Notes stripped off.
441
442
443
444
445
446
447
448
449
450
451

\begin{code}
tcSplitMethodTy :: Type -> (PredType, Type)
tcSplitMethodTy ty = split ty
 where
  split (FunTy arg res) = case tcSplitPredTy_maybe arg of
			    Just p  -> (p, res)
			    Nothing -> panic "splitMethodTy"
  split (NoteTy n ty)	= split ty
  split _               = panic "splitMethodTy"

452
tcSplitDFunTy :: Type -> ([TyVar], [PredType], Class, [Type])
453
454
455
456
457
-- Split the type of a dictionary function
tcSplitDFunTy ty 
  = case tcSplitSigmaTy ty       of { (tvs, theta, tau) ->
    case tcSplitPredTy_maybe tau of { Just (ClassP clas tys) -> 
    (tvs, theta, clas, tys) }}
458
459
\end{code}

460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
(allDistinctTyVars tys tvs) = True 
	iff 
all the types tys are type variables, 
distinct from each other and from tvs.

This is useful when checking that unification hasn't unified signature
type variables.  For example, if the type sig is
	f :: forall a b. a -> b -> b
we want to check that 'a' and 'b' havn't 
	(a) been unified with a non-tyvar type
	(b) been unified with each other (all distinct)
	(c) been unified with a variable free in the environment

\begin{code}
allDistinctTyVars :: [Type] -> TyVarSet -> Bool

allDistinctTyVars []       acc
  = True
allDistinctTyVars (ty:tys) acc 
  = case tcGetTyVar_maybe ty of
	Nothing 		      -> False 	-- (a)
	Just tv | tv `elemVarSet` acc -> False	-- (b) or (c)
		| otherwise           -> allDistinctTyVars tys (acc `extendVarSet` tv)
\end{code}    

485
486
487

%************************************************************************
%*									*
488
\subsection{Predicate types}
489
490
%*									*
%************************************************************************
491

492
\begin{code}
493
494
tcSplitPredTy_maybe :: Type -> Maybe PredType
   -- Returns Just for predicates only
495
496
497
tcSplitPredTy_maybe (NoteTy _ ty) = tcSplitPredTy_maybe ty
tcSplitPredTy_maybe (PredTy p)  = Just p
tcSplitPredTy_maybe other	  = Nothing
498
	
499
predTyUnique :: PredType -> Unique
500
predTyUnique (IParam n _)      = getUnique (ipNameName n)
501
502
predTyUnique (ClassP clas tys) = getUnique clas

503
mkPredName :: Unique -> SrcLoc -> PredType -> Name
504
505
mkPredName uniq loc (ClassP cls tys) = mkInternalName uniq (mkDictOcc (getOccName cls)) loc
mkPredName uniq loc (IParam ip ty)   = mkInternalName uniq (getOccName (ipNameName ip)) loc
506
507
\end{code}

508
509

--------------------- Dictionary types ---------------------------------
510
511

\begin{code}
512
mkClassPred clas tys = ClassP clas tys
513

514
isClassPred :: PredType -> Bool
515
516
517
isClassPred (ClassP clas tys) = True
isClassPred other	      = False

518
isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
519
520
isTyVarClassPred other		   = False

521
getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
522
523
524
525
526
527
528
getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
getClassPredTys_maybe _		        = Nothing

getClassPredTys :: PredType -> (Class, [Type])
getClassPredTys (ClassP clas tys) = (clas, tys)

mkDictTy :: Class -> [Type] -> Type
529
mkDictTy clas tys = mkPredTy (ClassP clas tys)
530
531

isDictTy :: Type -> Bool
532
isDictTy (PredTy p)   = isClassPred p
533
534
isDictTy (NoteTy _ ty)	= isDictTy ty
isDictTy other		= False
535
\end{code}
536

537
538
539
--------------------- Implicit parameters ---------------------------------

\begin{code}
540
isIPPred :: PredType -> Bool
541
542
543
isIPPred (IParam _ _) = True
isIPPred other	      = False

544
isInheritablePred :: PredType -> Bool
545
546
547
548
549
550
551
552
-- Can be inherited by a context.  For example, consider
--	f x = let g y = (?v, y+x)
--	      in (g 3 with ?v = 8, 
--		  g 4 with ?v = 9)
-- The point is that g's type must be quantifed over ?v:
--	g :: (?v :: a) => a -> a
-- but it doesn't need to be quantified over the Num a dictionary
-- which can be free in g's rhs, and shared by both calls to g
553
554
555
556
557
558
isInheritablePred (ClassP _ _) = True
isInheritablePred other	     = False

isLinearPred :: TcPredType -> Bool
isLinearPred (IParam (Linear n) _) = True
isLinearPred other		   = False
559
\end{code}
560
561


562
563
%************************************************************************
%*									*
564
\subsection{Comparison}
565
566
%*									*
%************************************************************************
567

568
569
Comparison, taking note of newtypes, predicates, etc,

570
\begin{code}
571
572
573
tcEqType :: Type -> Type -> Bool
tcEqType ty1 ty2 = case ty1 `tcCmpType` ty2 of { EQ -> True; other -> False }

574
575
576
tcEqTypes :: [Type] -> [Type] -> Bool
tcEqTypes ty1 ty2 = case ty1 `tcCmpTypes` ty2 of { EQ -> True; other -> False }

577
578
579
580
581
582
583
584
585
tcEqPred :: PredType -> PredType -> Bool
tcEqPred p1 p2 = case p1 `tcCmpPred` p2 of { EQ -> True; other -> False }

-------------
tcCmpType :: Type -> Type -> Ordering
tcCmpType ty1 ty2 = cmpTy emptyVarEnv ty1 ty2

tcCmpTypes tys1 tys2 = cmpTys emptyVarEnv tys1 tys2

586
tcCmpPred p1 p2 = cmpPredTy emptyVarEnv p1 p2
587
588
589
590
591
592
593
594
595
-------------
cmpTys env tys1 tys2 = cmpList (cmpTy env) tys1 tys2

-------------
cmpTy :: TyVarEnv TyVar -> Type -> Type -> Ordering
  -- The "env" maps type variables in ty1 to type variables in ty2
  -- So when comparing for-alls.. (forall tv1 . t1) (forall tv2 . t2)
  -- we in effect substitute tv2 for tv1 in t1 before continuing

596
    -- Look through NoteTy
597
598
599
600
601
602
603
604
cmpTy env (NoteTy _ ty1) ty2 = cmpTy env ty1 ty2
cmpTy env ty1 (NoteTy _ ty2) = cmpTy env ty1 ty2

    -- Deal with equal constructors
cmpTy env (TyVarTy tv1) (TyVarTy tv2) = case lookupVarEnv env tv1 of
					  Just tv1a -> tv1a `compare` tv2
					  Nothing   -> tv1  `compare` tv2

605
cmpTy env (PredTy p1) (PredTy p2) = cmpPredTy env p1 p2
606
607
608
cmpTy env (AppTy f1 a1) (AppTy f2 a2) = cmpTy env f1 f2 `thenCmp` cmpTy env a1 a2
cmpTy env (FunTy f1 a1) (FunTy f2 a2) = cmpTy env f1 f2 `thenCmp` cmpTy env a1 a2
cmpTy env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
609
cmpTy env (NewTcApp tc1 tys1) (NewTcApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
610
611
cmpTy env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   = cmpTy (extendVarEnv env tv1 tv2) t1 t2
    
612
    -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < NewTcApp < ForAllTy < PredTy
613
614
615
616
617
618
619
620
621
cmpTy env (AppTy _ _) (TyVarTy _) = GT
    
cmpTy env (FunTy _ _) (TyVarTy _) = GT
cmpTy env (FunTy _ _) (AppTy _ _) = GT
    
cmpTy env (TyConApp _ _) (TyVarTy _) = GT
cmpTy env (TyConApp _ _) (AppTy _ _) = GT
cmpTy env (TyConApp _ _) (FunTy _ _) = GT
    
622
623
624
625
626
cmpTy env (NewTcApp _ _) (TyVarTy _) 	= GT
cmpTy env (NewTcApp _ _) (AppTy _ _) 	= GT
cmpTy env (NewTcApp _ _) (FunTy _ _) 	= GT
cmpTy env (NewTcApp _ _) (TyConApp _ _) = GT
    
627
628
629
630
cmpTy env (ForAllTy _ _) (TyVarTy _)    = GT
cmpTy env (ForAllTy _ _) (AppTy _ _)    = GT
cmpTy env (ForAllTy _ _) (FunTy _ _)    = GT
cmpTy env (ForAllTy _ _) (TyConApp _ _) = GT
631
cmpTy env (ForAllTy _ _) (NewTcApp _ _) = GT
632

633
cmpTy env (PredTy _)   t2		= GT
634
635

cmpTy env _ _ = LT
636
637
638
\end{code}

\begin{code}
639
640
cmpPredTy :: TyVarEnv TyVar -> PredType -> PredType -> Ordering
cmpPredTy env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` (cmpTy env ty1 ty2)
641
642
643
	-- Compare types as well as names for implicit parameters
	-- This comparison is used exclusively (I think) for the
	-- finite map built in TcSimplify
644
645
646
cmpPredTy env (IParam _ _)     (ClassP _ _)	  = LT
cmpPredTy env (ClassP _ _)     (IParam _ _)     = GT
cmpPredTy env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTys env tys1 tys2)
647
\end{code}
648

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

\begin{code}
653
654
instance Eq  PredType where { (==)    = tcEqPred }
instance Ord PredType where { compare = tcCmpPred }
655
656
\end{code}

657

658
659
660
661
662
%************************************************************************
%*									*
\subsection{Predicates}
%*									*
%************************************************************************
663

664
isSigmaTy returns true of any qualified type.  It doesn't *necessarily* have 
665
666
any foralls.  E.g.
	f :: (?x::Int) => Int -> Int
667

668
\begin{code}
669
670
671
672
673
isSigmaTy :: Type -> Bool
isSigmaTy (ForAllTy tyvar ty) = True
isSigmaTy (FunTy a b)	      = isPredTy a
isSigmaTy (NoteTy n ty)	      = isSigmaTy ty
isSigmaTy _		      = False
674
675
676
677
678
679

isOverloadedTy :: Type -> Bool
isOverloadedTy (ForAllTy tyvar ty) = isOverloadedTy ty
isOverloadedTy (FunTy a b)	   = isPredTy a
isOverloadedTy (NoteTy n ty)	   = isOverloadedTy ty
isOverloadedTy _		   = False
680
681
682
683
684
685

isPredTy :: Type -> Bool	-- Belongs in TcType because it does 
				-- not look through newtypes, or predtypes (of course)
isPredTy (NoteTy _ ty) = isPredTy ty
isPredTy (PredTy sty)  = True
isPredTy _	       = False
686
\end{code}
687
688

\begin{code}
689
690
691
692
693
694
isFloatTy      = is_tc floatTyConKey
isDoubleTy     = is_tc doubleTyConKey
isIntegerTy    = is_tc integerTyConKey
isIntTy        = is_tc intTyConKey
isAddrTy       = is_tc addrTyConKey
isBoolTy       = is_tc boolTyConKey
695
isUnitTy       = is_tc unitTyConKey
696
697
698
699
700
701
702

is_tc :: Unique -> Type -> Bool
-- Newtypes are opaque to this
is_tc uniq ty = case tcSplitTyConApp_maybe ty of
			Just (tc, _) -> uniq == getUnique tc
			Nothing	     -> False
\end{code}
703

704

705
706
707
708
709
710
711
712
%************************************************************************
%*									*
\subsection{Misc}
%*									*
%************************************************************************

\begin{code}
deNoteType :: Type -> Type
713
	-- Remove synonyms, but not predicate types
714
715
deNoteType ty@(TyVarTy tyvar)	= ty
deNoteType (TyConApp tycon tys) = TyConApp tycon (map deNoteType tys)
716
717
deNoteType (NewTcApp tycon tys) = NewTcApp tycon (map deNoteType tys)
deNoteType (PredTy p)		= PredTy (deNotePredType p)
718
719
720
721
722
deNoteType (NoteTy _ ty)	= deNoteType ty
deNoteType (AppTy fun arg)	= AppTy (deNoteType fun) (deNoteType arg)
deNoteType (FunTy fun arg)	= FunTy (deNoteType fun) (deNoteType arg)
deNoteType (ForAllTy tv ty)	= ForAllTy tv (deNoteType ty)

723
724
725
deNotePredType :: PredType -> PredType
deNotePredType (ClassP c tys)   = ClassP c (map deNoteType tys)
deNotePredType (IParam n ty)    = IParam n (deNoteType ty)
726
727
\end{code}

728
729
Find the free tycons and classes of a type.  This is used in the front
end of the compiler.
730

731
\begin{code}
732
733
734
tyClsNamesOfType :: Type -> NameSet
tyClsNamesOfType (TyVarTy tv)		    = emptyNameSet
tyClsNamesOfType (TyConApp tycon tys)	    = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
735
tyClsNamesOfType (NewTcApp tycon tys)	    = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
736
737
tyClsNamesOfType (NoteTy (SynNote ty1) ty2) = tyClsNamesOfType ty1
tyClsNamesOfType (NoteTy other_note    ty2) = tyClsNamesOfType ty2
738
739
tyClsNamesOfType (PredTy (IParam n ty))   = tyClsNamesOfType ty
tyClsNamesOfType (PredTy (ClassP cl tys)) = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
740
741
742
743
744
745
746
tyClsNamesOfType (FunTy arg res)	    = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
tyClsNamesOfType (AppTy fun arg)	    = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
tyClsNamesOfType (ForAllTy tyvar ty)	    = tyClsNamesOfType ty

tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys

tyClsNamesOfDFunHead :: Type -> NameSet
747
748
749
750
751
752
-- Find the free type constructors and classes 
-- of the head of the dfun instance type
-- The 'dfun_head_type' is because of
--	instance Foo a => Baz T where ...
-- The decl is an orphan if Baz and T are both not locally defined,
--	even if Foo *is* locally defined
753
754
755
756
tyClsNamesOfDFunHead dfun_ty 
  = case tcSplitSigmaTy dfun_ty of
	(tvs,_,head_ty) -> tyClsNamesOfType head_ty

757
classesOfTheta :: ThetaType -> [Class]
758
-- Looks just for ClassP things; maybe it should check
759
classesOfTheta preds = [ c | ClassP c _ <- preds ]
760
761
762
\end{code}


763
764
765
766
767
768
769
770
771
772
773
%************************************************************************
%*									*
\subsection[TysWiredIn-ext-type]{External types}
%*									*
%************************************************************************

The compiler's foreign function interface supports the passing of a
restricted set of types as arguments and results (the restricting factor
being the )

\begin{code}
774
775
776
777
isFFITy :: Type -> Bool
-- True for any TyCon that can possibly be an arg or result of an FFI call
isFFITy ty = checkRepTyCon legalFFITyCon ty

778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
-- Checks for valid argument type for a 'foreign import'
isFFIArgumentTy dflags safety ty 
   = checkRepTyCon (legalOutgoingTyCon dflags safety) ty

isFFIExternalTy :: Type -> Bool
-- Types that are allowed as arguments of a 'foreign export'
isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty

isFFIImportResultTy :: DynFlags -> Type -> Bool
isFFIImportResultTy dflags ty 
  = checkRepTyCon (legalFIResultTyCon dflags) ty

isFFIExportResultTy :: Type -> Bool
isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty

isFFIDynArgumentTy :: Type -> Bool
-- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
-- or a newtype of either.
797
isFFIDynArgumentTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey, addrTyConKey]
798
799
800
801

isFFIDynResultTy :: Type -> Bool
-- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
-- or a newtype of either.
802
isFFIDynResultTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey, addrTyConKey]
803
804
805
806

isFFILabelTy :: Type -> Bool
-- The type of a foreign label must be Ptr, FunPtr, Addr,
-- or a newtype of either.
807
isFFILabelTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey, addrTyConKey]
808

sof's avatar
sof committed
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
isFFIDotnetTy :: DynFlags -> Type -> Bool
isFFIDotnetTy dflags ty
  = checkRepTyCon (\ tc -> not (isByteArrayLikeTyCon tc) &&
  			   (legalFIResultTyCon dflags tc || 
			   isFFIDotnetObjTy ty || isStringTy ty)) ty

-- Support String as an argument or result from a .NET FFI call.
isStringTy ty = 
  case tcSplitTyConApp_maybe (repType ty) of
    Just (tc, [arg_ty])
      | tc == listTyCon ->
        case tcSplitTyConApp_maybe (repType arg_ty) of
	  Just (cc,[]) -> cc == charTyCon
	  _ -> False
    _ -> False

-- Support String as an argument or result from a .NET FFI call.
isFFIDotnetObjTy ty = 
  let
   (_, t_ty) = tcSplitForAllTys ty
  in
  case tcSplitTyConApp_maybe (repType t_ty) of
    Just (tc, [arg_ty]) | getName tc == objectTyConName -> True
    _ -> False

toDNType :: Type -> DNType
toDNType ty
  | isStringTy ty = DNString
  | isFFIDotnetObjTy ty = DNObject
  | Just (tc,argTys) <- tcSplitTyConApp_maybe ty = 
     case lookup (getUnique tc) dn_assoc of
       Just x  -> x
       Nothing 
         | tc `hasKey` ioTyConKey -> toDNType (head argTys)
	 | otherwise -> pprPanic ("toDNType: unsupported .NET type") (pprType ty <+> parens (hcat (map pprType argTys)) <+> ppr tc)
    where
      dn_assoc :: [ (Unique, DNType) ]
      dn_assoc = [ (unitTyConKey,   DNUnit)
      		 , (intTyConKey,    DNInt)
      	         , (int8TyConKey,   DNInt8)
		 , (int16TyConKey,  DNInt16)
		 , (int32TyConKey,  DNInt32)
		 , (int64TyConKey,  DNInt64)
		 , (wordTyConKey,   DNInt)
		 , (word8TyConKey,  DNWord8)
		 , (word16TyConKey, DNWord16)
		 , (word32TyConKey, DNWord32)
		 , (word64TyConKey, DNWord64)
		 , (floatTyConKey,  DNFloat)
		 , (doubleTyConKey, DNDouble)
		 , (addrTyConKey,   DNPtr)
		 , (ptrTyConKey,    DNPtr)
		 , (funPtrTyConKey, DNPtr)
		 , (charTyConKey,   DNChar)
		 , (boolTyConKey,   DNBool)
		 ]

866
867
868
checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
	-- Look through newtypes
	-- Non-recursive ones are transparent to splitTyConApp,
869
	-- but recursive ones aren't
870
checkRepTyCon check_tc ty 
871
872
  | Just (tc,_) <- splitTyConApp_maybe (repType ty) = check_tc tc
  | otherwise				  	    = False
873
874
875
876
877

checkRepTyConKey :: [Unique] -> Type -> Bool
-- Like checkRepTyCon, but just looks at the TyCon key
checkRepTyConKey keys
  = checkRepTyCon (\tc -> tyConUnique tc `elem` keys)
878
879
880
881
882
883
884
885
886
887
888
889
\end{code}

----------------------------------------------
These chaps do the work; they are not exported
----------------------------------------------

\begin{code}
legalFEArgTyCon :: TyCon -> Bool
-- It's illegal to return foreign objects and (mutable)
-- bytearrays from a _ccall_ / foreign declaration
-- (or be passed them as arguments in foreign exported functions).
legalFEArgTyCon tc
sof's avatar
sof committed
890
  | isByteArrayLikeTyCon tc
891
892
893
894
895
896
897
898
  = False
  -- It's also illegal to make foreign exports that take unboxed
  -- arguments.  The RTS API currently can't invoke such things.  --SDM 7/2000
  | otherwise
  = boxedMarshalableTyCon tc

legalFIResultTyCon :: DynFlags -> TyCon -> Bool
legalFIResultTyCon dflags tc
sof's avatar
sof committed
899
900
901
  | isByteArrayLikeTyCon tc = False
  | tc == unitTyCon         = True
  | otherwise	            = marshalableTyCon dflags tc
902
903
904

legalFEResultTyCon :: TyCon -> Bool
legalFEResultTyCon tc
sof's avatar
sof committed
905
906
907
  | isByteArrayLikeTyCon tc = False
  | tc == unitTyCon         = True
  | otherwise               = boxedMarshalableTyCon tc
908
909
910
911

legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
-- Checks validity of types going from Haskell -> external world
legalOutgoingTyCon dflags safety tc
sof's avatar
sof committed
912
  | playSafe safety && isByteArrayLikeTyCon tc
913
914
915
916
  = False
  | otherwise
  = marshalableTyCon dflags tc

917
918
919
920
921
legalFFITyCon :: TyCon -> Bool
-- True for any TyCon that can possibly be an arg or result of an FFI call
legalFFITyCon tc
  = isUnLiftedTyCon tc || boxedMarshalableTyCon tc || tc == unitTyCon

922
923
924
925
926
927
928
929
930
931
932
marshalableTyCon dflags tc
  =  (dopt Opt_GlasgowExts dflags && isUnLiftedTyCon tc)
  || boxedMarshalableTyCon tc

boxedMarshalableTyCon tc
   = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
			 , int32TyConKey, int64TyConKey
			 , wordTyConKey, word8TyConKey, word16TyConKey
			 , word32TyConKey, word64TyConKey
			 , floatTyConKey, doubleTyConKey
			 , addrTyConKey, ptrTyConKey, funPtrTyConKey
933
			 , charTyConKey
934
935
936
937
			 , stablePtrTyConKey
			 , byteArrayTyConKey, mutableByteArrayTyConKey
			 , boolTyConKey
			 ]
sof's avatar
sof committed
938
939
940
941

isByteArrayLikeTyCon :: TyCon -> Bool
isByteArrayLikeTyCon tc = 
  getUnique tc `elem` [byteArrayTyConKey, mutableByteArrayTyConKey]
942
943
944
\end{code}


945
946
947
948
949
950
951
952
%************************************************************************
%*									*
\subsection{Unification with an explicit substitution}
%*									*
%************************************************************************

Unify types with an explicit substitution and no monad.
Ignore usage annotations.
953
954

\begin{code}
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
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
type MySubst
   = (TyVarSet,		-- Set of template tyvars
      TyVarSubstEnv)	-- Not necessarily idempotent

unifyTysX :: TyVarSet		-- Template tyvars
	  -> Type
          -> Type
          -> Maybe TyVarSubstEnv
unifyTysX tmpl_tyvars ty1 ty2
  = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)

unifyExtendTysX :: TyVarSet		-- Template tyvars
		-> TyVarSubstEnv	-- Substitution to start with
		-> Type
	        -> Type
        	-> Maybe TyVarSubstEnv	-- Extended substitution
unifyExtendTysX tmpl_tyvars subst ty1 ty2
  = uTysX ty1 ty2 (\(_,s) -> Just s) (tmpl_tyvars, subst)

unifyTyListsX :: TyVarSet -> [Type] -> [Type]
              -> Maybe TyVarSubstEnv
unifyTyListsX tmpl_tyvars tys1 tys2
  = uTyListsX tys1 tys2 (\(_,s) -> Just s) (tmpl_tyvars, emptySubstEnv)


uTysX :: Type
      -> Type
      -> (MySubst -> Maybe result)
      -> MySubst
      -> Maybe result

uTysX (NoteTy _ ty1) ty2 k subst = uTysX ty1 ty2 k subst
uTysX ty1 (NoteTy _ ty2) k subst = uTysX ty1 ty2 k subst

	-- Variables; go for uVar
uTysX (TyVarTy tyvar1) (TyVarTy tyvar2) k subst 
  | tyvar1 == tyvar2
  = k subst
uTysX (TyVarTy tyvar1) ty2 k subst@(tmpls,_)
  | tyvar1 `elemVarSet` tmpls
  = uVarX tyvar1 ty2 k subst
uTysX ty1 (TyVarTy tyvar2) k subst@(tmpls,_)
  | tyvar2 `elemVarSet` tmpls
  = uVarX tyvar2 ty1 k subst

1000
	-- Predicates