TcType.lhs 38.5 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
26
  TyVarDetails(..), isUserTyVar, isSkolemTyVar, isHoleTyVar, 
  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
38
39
40
41
42
43
  tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy,
  tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
  tcSplitAppTy_maybe, tcSplitAppTy, tcSplitSigmaTy,
  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, 
54
55
56
57
58
  namesOfType, namesOfDFunHead,
  getDFunTyKey,

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

65
66
67
68
69
70
71
72
73
74
  ---------------------------------
  -- 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

75
76
77
78
  ---------------------------------
  -- Unifier and matcher  
  unifyTysX, unifyTyListsX, unifyExtendTysX,
  matchTy, matchTys, match,
79

80
81
  --------------------------------
  -- Rexported from Type
82
83
84
  Kind, 	-- Stuff to do with kinds is insensitive to pre/post Tc
  unliftedTypeKind, liftedTypeKind, openTypeKind, mkArrowKind, mkArrowKinds, 
  superBoxity, liftedBoxity, hasMoreBoxityInfo, defaultKind, superKind,
85
  isTypeKind, isAnyTypeKind,
86
87

  Type, SourceType(..), PredType, ThetaType, 
88
89
  mkForAllTy, mkForAllTys, 
  mkFunTy, mkFunTys, zipFunTys, 
90
  mkTyConApp, mkGenTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
91
  mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys, 
92

93
94
  isUnLiftedType,	-- Source types are always lifted
  isUnboxedTupleType,	-- Ditto
95
  isPrimitiveType, isTyVarTy,
96

97
  tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
98
  tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars,
99
  typeKind, eqKind, eqUsage,
100
101

  tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta
102
103
  ) where

104
#include "HsVersions.h"
105
106


107
108
import {-# SOURCE #-} PprType( pprType )

109
-- friends:
110
111
112
113
import TypeRep		( Type(..), TyNote(..), funTyCon )  -- friend

import Type		(	-- Re-exports
			  tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
114
			  Kind, Type, SourceType(..), PredType, ThetaType, 
115
			  unliftedTypeKind, liftedTypeKind, openTypeKind, mkArrowKind, mkArrowKinds,
116
			  mkForAllTy, mkForAllTys, defaultKind, isTypeKind, isAnyTypeKind,
117
			  mkFunTy, mkFunTys, zipFunTys, isTyVarTy,
118
			  mkTyConApp, mkGenTyConApp, mkAppTy, mkAppTys, mkSynTy, applyTy, applyTys,
119
120
121
			  mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
			  isUnLiftedType, isUnboxedTupleType, isPrimitiveType,
			  splitNewType_maybe, splitTyConApp_maybe,
122
			  tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
123
			  tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars, eqKind, eqUsage,
124
			  hasMoreBoxityInfo, liftedBoxity, superBoxity, typeKind, superKind
125
			)
126
127
import TyCon		( TyCon, isUnLiftedTyCon )
import Class		( classHasFDs, Class )
128
import Var		( TyVar, tyVarKind, isMutTyVar, mutTyVarDetails )
129
import ForeignCall	( Safety, playSafe )
130
131
import VarEnv
import VarSet
132
133

-- others:
134
import CmdLineOpts	( DynFlags, DynFlag( Opt_GlasgowExts ), dopt )
135
import Name		( Name, NamedThing(..), mkInternalName, getSrcLoc )
136
137
import OccName		( OccName, mkDictOcc )
import NameSet
138
import PrelNames	-- Lots (e.g. in isFFIArgumentTy)
139
import TysWiredIn	( ptrTyCon, funPtrTyCon, addrTyCon, unitTyCon )
140
import BasicTypes	( IPName(..), ipNameName )
141
import Unique		( Unique, Uniquable(..) )
142
import SrcLoc		( SrcLoc )
sof's avatar
sof committed
143
import Util		( cmpList, thenCmp, equalLength )
144
import Maybes		( maybeToBool, expectJust )
145
import Outputable
146
147
148
\end{code}


149
150
%************************************************************************
%*									*
151
152
153
154
\subsection{Types}
%*									*
%************************************************************************

155
156
157
The type checker divides the generic Type world into the 
following more structured beasts:

158
sigma ::= forall tyvars. phi
159
160
161
162
163
164
165
166
167
168
	-- 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

169
170
171
phi :: theta => rho

rho ::= sigma -> rho
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
     |  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.


\begin{code}
type SigmaType = Type
187
type RhoType   = Type
188
189
190
type TauType   = Type
\end{code}

191
192
193
194
195
196
197
198
199
200
201
202
\begin{code}
type TcTyVar    = TyVar		-- Might be a mutable tyvar
type TcTyVarSet = TyVarSet

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
203
type TcSigmaType    = TcType
204
type TcRhoType      = TcType
205
type TcTauType      = TcType
206
207
208
209
210
211
212
type TcKind         = TcType
\end{code}


%************************************************************************
%*									*
\subsection{TyVarDetails}
213
214
215
%*									*
%************************************************************************

216
217
TyVarDetails gives extra info about type variables, used during type
checking.  It's attached to mutable type variables only.
218
219
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.
220

221
\begin{code}
222
data TyVarDetails
223
224
225
226
227
228
  = HoleTv	-- Used *only* by the type checker when passing in a type
		-- variable that should be side-effected to the result type.
		-- Always has kind openTypeKind.
		-- Never appears in types

  | SigTv	-- Introduced when instantiating a type signature,
229
230
231
232
233
234
235
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

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

   | VanillaTv	-- Everything else

248
249
250
251
252
253
254
isUserTyVar :: TcTyVar -> Bool	-- Avoid unifying these if possible
isUserTyVar tv = case mutTyVarDetails tv of
		   VanillaTv -> False
		   other     -> True

isSkolemTyVar :: TcTyVar -> Bool
isSkolemTyVar tv = case mutTyVarDetails tv of
255
256
257
		      SigTv  -> True
		      ClsTv  -> True
		      InstTv -> True
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
		      oteher -> False

isHoleTyVar :: TcTyVar -> Bool
-- NB:  the hole might be filled in by now, and this
--	function does not check for that
isHoleTyVar tv = ASSERT( isMutTyVar tv )
		 case mutTyVarDetails tv of
			HoleTv -> True
			other  -> False

tyVarBindingInfo :: TyVar -> SDoc	-- Used in checkSigTyVars
tyVarBindingInfo tv
  | isMutTyVar tv
  = sep [ptext SLIT("is bound by the") <+> details (mutTyVarDetails tv),
	 ptext SLIT("at") <+> ppr (getSrcLoc tv)]
  | otherwise
  = empty
  where
    details SigTv     = ptext SLIT("type signature")
    details ClsTv     = ptext SLIT("class declaration")
    details InstTv    = ptext SLIT("instance declaration")
    details PatSigTv  = ptext SLIT("pattern type signature")
    details HoleTv    = ptext SLIT("//hole//")		-- Should not happen
    details VanillaTv = ptext SLIT("//vanilla//")	-- Ditto
282
\end{code}
283

284
285
286
287
288
289
290
291

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

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

294
295
mkPhiTy :: [SourceType] -> Type -> Type
mkPhiTy theta ty = foldr (\p r -> FunTy (mkPredTy p) r) ty theta
296
297
298
299
\end{code}


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

301
\begin{code}
302
303
304
305
306
isTauTy :: Type -> Bool
isTauTy (TyVarTy v)	 = True
isTauTy (TyConApp _ tys) = all isTauTy tys
isTauTy (AppTy a b)	 = isTauTy a && isTauTy b
isTauTy (FunTy a b)	 = isTauTy a && isTauTy b
307
isTauTy (SourceTy p)	 = True		-- Don't look through source types
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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
getDFunTyKey (TyVarTy tv)    	     = getOccName tv
getDFunTyKey (TyConApp tc _) 	     = getOccName tc
getDFunTyKey (AppTy fun _)   	     = getDFunTyKey fun
getDFunTyKey (NoteTy _ t)    	     = getDFunTyKey t
getDFunTyKey (FunTy arg _)   	     = getOccName funTyCon
getDFunTyKey (ForAllTy _ t)  	     = getDFunTyKey t
getDFunTyKey (SourceTy (NType tc _)) = getOccName tc	-- Newtypes are quite reasonable
getDFunTyKey ty		     	     = pprPanic "getDFunTyKey" (pprType ty)
-- SourceTy shouldn't happen
sof's avatar
sof committed
324
325
326
\end{code}


327
328
%************************************************************************
%*									*
329
\subsection{Expanding and splitting}
330
331
%*									*
%************************************************************************
332

333
334
335
336
337
338
339
340
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.

341
\begin{code}
342
343
344
345
346
347
348
349
350
351
352
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

353
354
tcSplitPhiTy :: Type -> ([PredType], Type)
tcSplitPhiTy ty = split ty ty []
355
356
357
358
359
360
361
362
 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
363
			(tvs, rho) -> case tcSplitPhiTy rho of
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
					(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])
tcSplitTyConApp_maybe (TyConApp tc tys) 	= Just (tc, tys)
379
tcSplitTyConApp_maybe (FunTy arg res)   	= Just (funTyCon, [arg,res])
380
381
tcSplitTyConApp_maybe (NoteTy n ty)     	= tcSplitTyConApp_maybe ty
tcSplitTyConApp_maybe (SourceTy (NType tc tys)) = Just (tc,tys)
382
	-- Newtypes are opaque, so they may be split
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
	-- 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)
404
tcSplitAppTy_maybe (FunTy ty1 ty2)   	     = Just (TyConApp funTyCon [ty1], ty2)
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
tcSplitAppTy_maybe (AppTy ty1 ty2)   	     = Just (ty1, ty2)
tcSplitAppTy_maybe (NoteTy n ty)     	     = tcSplitAppTy_maybe ty
tcSplitAppTy_maybe (SourceTy (NType tc tys)) = tc_split_app tc tys
	--- Don't forget that newtype!
tcSplitAppTy_maybe (TyConApp tc tys)	     = tc_split_app tc tys
tcSplitAppTy_maybe other	  	     = Nothing

tc_split_app tc []  = Nothing
tc_split_app tc tys = split tys []
		    where
		      split [ty2]    acc = Just (TyConApp tc (reverse acc), ty2)
		      split (ty:tys) acc = split tys (ty:acc)

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

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
returns (C a1..an, sig_ty') where sig_ty' is sig_ty with any Notes or
Usages stripped off.

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

tcSplitDFunTy :: Type -> ([TyVar], [SourceType], Class, [Type])
-- 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
"Predicates" are particular source types, namelyClassP or IParams
493

494
\begin{code}
495
496
497
isPred :: SourceType -> Bool
isPred (ClassP _ _) = True
isPred (IParam _ _) = True
498
isPred (NType _ _)  = False
499
500
501
502
503
504
505
506
507
508
509

isPredTy :: Type -> Bool
isPredTy (NoteTy _ ty)  = isPredTy ty
isPredTy (SourceTy sty) = isPred sty
isPredTy _	        = False

tcSplitPredTy_maybe :: Type -> Maybe PredType
   -- Returns Just for predicates only
tcSplitPredTy_maybe (NoteTy _ ty)  	    = tcSplitPredTy_maybe ty
tcSplitPredTy_maybe (SourceTy p) | isPred p = Just p
tcSplitPredTy_maybe other	      	    = Nothing
510
	
511
predTyUnique :: PredType -> Unique
512
predTyUnique (IParam n _)      = getUnique (ipNameName n)
513
514
515
516
517
518
519
520
521
predTyUnique (ClassP clas tys) = getUnique clas

predHasFDs :: PredType -> Bool
-- True if the predicate has functional depenencies; 
-- I.e. should participate in improvement
predHasFDs (IParam _ _)   = True
predHasFDs (ClassP cls _) = classHasFDs cls

mkPredName :: Unique -> SrcLoc -> SourceType -> Name
522
523
mkPredName uniq loc (ClassP cls tys) = mkInternalName uniq (mkDictOcc (getOccName cls)) loc
mkPredName uniq loc (IParam ip ty)   = mkInternalName uniq (getOccName (ipNameName ip)) loc
524
525
\end{code}

526
527

--------------------- Dictionary types ---------------------------------
528
529

\begin{code}
530
mkClassPred clas tys = ClassP clas tys
531
532
533
534
535

isClassPred :: SourceType -> Bool
isClassPred (ClassP clas tys) = True
isClassPred other	      = False

536
isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
537
538
539
540
541
542
543
544
545
546
isTyVarClassPred other		   = False

getClassPredTys_maybe :: SourceType -> Maybe (Class, [Type])
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
547
mkDictTy clas tys = mkPredTy (ClassP clas tys)
548
549
550
551
552

isDictTy :: Type -> Bool
isDictTy (SourceTy p)   = isClassPred p
isDictTy (NoteTy _ ty)	= isDictTy ty
isDictTy other		= False
553
\end{code}
554

555
556
557
558
559
560
561
--------------------- Implicit parameters ---------------------------------

\begin{code}
isIPPred :: SourceType -> Bool
isIPPred (IParam _ _) = True
isIPPred other	      = False

562
isInheritablePred :: PredType -> Bool
563
564
565
566
567
568
569
570
-- 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
571
572
573
574
575
576
isInheritablePred (ClassP _ _) = True
isInheritablePred other	     = False

isLinearPred :: TcPredType -> Bool
isLinearPred (IParam (Linear n) _) = True
isLinearPred other		   = False
577
\end{code}
578
579


580
581
%************************************************************************
%*									*
582
\subsection{Comparison}
583
584
%*									*
%************************************************************************
585

586
587
588
Comparison, taking note of newtypes, predicates, etc,
But ignoring usage types

589
\begin{code}
590
591
592
tcEqType :: Type -> Type -> Bool
tcEqType ty1 ty2 = case ty1 `tcCmpType` ty2 of { EQ -> True; other -> False }

593
594
595
tcEqTypes :: [Type] -> [Type] -> Bool
tcEqTypes ty1 ty2 = case ty1 `tcCmpTypes` ty2 of { EQ -> True; other -> False }

596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
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

tcCmpPred p1 p2 = cmpSourceTy emptyVarEnv p1 p2
-------------
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

615
    -- Look through NoteTy
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
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

cmpTy env (SourceTy p1) (SourceTy p2) = cmpSourceTy env p1 p2
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)
cmpTy env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   = cmpTy (extendVarEnv env tv1 tv2) t1 t2
    
    -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < SourceTy
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
    
cmpTy env (ForAllTy _ _) (TyVarTy _)    = GT
cmpTy env (ForAllTy _ _) (AppTy _ _)    = GT
cmpTy env (ForAllTy _ _) (FunTy _ _)    = GT
cmpTy env (ForAllTy _ _) (TyConApp _ _) = GT

cmpTy env (SourceTy _)   t2		= GT

cmpTy env _ _ = LT
648
649
650
\end{code}

\begin{code}
651
cmpSourceTy :: TyVarEnv TyVar -> SourceType -> SourceType -> Ordering
652
cmpSourceTy env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` (cmpTy env ty1 ty2)
653
654
655
656
657
658
659
660
661
662
663
664
	-- Compare types as well as names for implicit parameters
	-- This comparison is used exclusively (I think) for the
	-- finite map built in TcSimplify
cmpSourceTy env (IParam _ _)     sty		  = LT

cmpSourceTy env (ClassP _ _)     (IParam _ _)     = GT
cmpSourceTy env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTys env tys1 tys2)
cmpSourceTy env (ClassP _ _)     (NType _ _)      = LT

cmpSourceTy env (NType tc1 tys1) (NType tc2 tys2) = (tc1 `compare` tc2) `thenCmp` (cmpTys env tys1 tys2)
cmpSourceTy env (NType _ _)	 sty		  = GT
\end{code}
665

666
667
668
669
670
671
PredTypes are used as a FM key in TcSimplify, 
so we take the easy path and make them an instance of Ord

\begin{code}
instance Eq  SourceType where { (==)    = tcEqPred }
instance Ord SourceType where { compare = tcCmpPred }
672
673
\end{code}

674

675
676
677
678
679
%************************************************************************
%*									*
\subsection{Predicates}
%*									*
%************************************************************************
680

681
isSigmaTy returns true of any qualified type.  It doesn't *necessarily* have 
682
683
any foralls.  E.g.
	f :: (?x::Int) => Int -> Int
684

685
\begin{code}
686
687
688
689
690
isSigmaTy :: Type -> Bool
isSigmaTy (ForAllTy tyvar ty) = True
isSigmaTy (FunTy a b)	      = isPredTy a
isSigmaTy (NoteTy n ty)	      = isSigmaTy ty
isSigmaTy _		      = False
691
692
693
694
695
696
697

isOverloadedTy :: Type -> Bool
isOverloadedTy (ForAllTy tyvar ty) = isOverloadedTy ty
isOverloadedTy (FunTy a b)	   = isPredTy a
isOverloadedTy (NoteTy n ty)	   = isOverloadedTy ty
isOverloadedTy _		   = False
\end{code}
698
699

\begin{code}
700
701
702
703
704
705
isFloatTy      = is_tc floatTyConKey
isDoubleTy     = is_tc doubleTyConKey
isIntegerTy    = is_tc integerTyConKey
isIntTy        = is_tc intTyConKey
isAddrTy       = is_tc addrTyConKey
isBoolTy       = is_tc boolTyConKey
706
isUnitTy       = is_tc unitTyConKey
707
708
709
710
711
712
713

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

715

716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
%************************************************************************
%*									*
\subsection{Misc}
%*									*
%************************************************************************

\begin{code}
deNoteType :: Type -> Type
	-- Remove synonyms, but not source types
deNoteType ty@(TyVarTy tyvar)	= ty
deNoteType (TyConApp tycon tys) = TyConApp tycon (map deNoteType tys)
deNoteType (SourceTy p)		= SourceTy (deNoteSourceType p)
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)

deNoteSourceType :: SourceType -> SourceType
734
735
736
deNoteSourceType (ClassP c tys)   = ClassP c (map deNoteType tys)
deNoteSourceType (IParam n ty)    = IParam n (deNoteType ty)
deNoteSourceType (NType tc tys)   = NType tc (map deNoteType tys)
737
738
739
740
\end{code}

Find the free names of a type, including the type constructors and classes it mentions
This is used in the front end of the compiler
741

742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
\begin{code}
namesOfType :: Type -> NameSet
namesOfType (TyVarTy tv)		= unitNameSet (getName tv)
namesOfType (TyConApp tycon tys)	= unitNameSet (getName tycon) `unionNameSets` namesOfTypes tys
namesOfType (NoteTy (SynNote ty1) ty2)	= namesOfType ty1
namesOfType (NoteTy other_note    ty2)	= namesOfType ty2
namesOfType (SourceTy (IParam n ty))	= namesOfType ty
namesOfType (SourceTy (ClassP cl tys))	= unitNameSet (getName cl) `unionNameSets` namesOfTypes tys
namesOfType (SourceTy (NType tc tys))	= unitNameSet (getName tc) `unionNameSets` namesOfTypes tys
namesOfType (FunTy arg res)		= namesOfType arg `unionNameSets` namesOfType res
namesOfType (AppTy fun arg)		= namesOfType fun `unionNameSets` namesOfType arg
namesOfType (ForAllTy tyvar ty)		= namesOfType ty `delFromNameSet` getName tyvar

namesOfTypes tys = foldr (unionNameSets . namesOfType) emptyNameSet tys

namesOfDFunHead :: Type -> NameSet
-- 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
namesOfDFunHead dfun_ty = case tcSplitSigmaTy dfun_ty of
				(tvs,_,head_ty) -> delListFromNameSet (namesOfType head_ty)
								      (map getName tvs)
767
768
769
\end{code}


770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
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
822
823
824
825
826
827
828
829
830
831
%************************************************************************
%*									*
\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}
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.
isFFIDynArgumentTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)

isFFIDynResultTy :: Type -> Bool
-- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
-- or a newtype of either.
isFFIDynResultTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)

isFFILabelTy :: Type -> Bool
-- The type of a foreign label must be Ptr, FunPtr, Addr,
-- or a newtype of either.
isFFILabelTy = checkRepTyCon (\tc -> tc == ptrTyCon || tc == funPtrTyCon || tc == addrTyCon)

checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
	-- Look through newtypes
	-- Non-recursive ones are transparent to splitTyConApp,
	-- but recursive ones aren't; hence the splitNewType_maybe
checkRepTyCon check_tc ty 
  | Just ty'    <- splitNewType_maybe ty  = checkRepTyCon check_tc ty'
  | Just (tc,_) <- splitTyConApp_maybe ty = check_tc tc
  | otherwise				  = False
\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
832
  | getUnique tc `elem` [ foreignObjTyConKey, 
833
834
835
836
837
838
839
840
841
842
			  byteArrayTyConKey, mutableByteArrayTyConKey ] 
  = 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
  | getUnique tc `elem`
843
	[ foreignObjTyConKey,
844
845
846
847
848
849
850
	  byteArrayTyConKey, mutableByteArrayTyConKey ]  = False
  | tc == unitTyCon = True
  | otherwise	    = marshalableTyCon dflags tc

legalFEResultTyCon :: TyCon -> Bool
legalFEResultTyCon tc
  | getUnique tc `elem` 
851
	[ foreignObjTyConKey,
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
	  byteArrayTyConKey, mutableByteArrayTyConKey ]  = False
  | tc == unitTyCon = True
  | otherwise       = boxedMarshalableTyCon tc

legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
-- Checks validity of types going from Haskell -> external world
legalOutgoingTyCon dflags safety tc
  | playSafe safety && getUnique tc `elem` [byteArrayTyConKey, mutableByteArrayTyConKey]
  = False
  | otherwise
  = marshalableTyCon dflags tc

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
			 , charTyConKey, foreignObjTyConKey
			 , stablePtrTyConKey
			 , byteArrayTyConKey, mutableByteArrayTyConKey
			 , boolTyConKey
			 ]
\end{code}


883
884
885
886
887
888
889
890
%************************************************************************
%*									*
\subsection{Unification with an explicit substitution}
%*									*
%************************************************************************

Unify types with an explicit substitution and no monad.
Ignore usage annotations.
891
892

\begin{code}
893
894
895
896
897
898
899
900
901
902
903
904
905
906
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
932
933
934
935
936
937
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

938
939
940
941
942
943
944
945
	-- Predicates
uTysX (SourceTy (IParam n1 t1)) (SourceTy (IParam n2 t2)) k subst
  | n1 == n2 = uTysX t1 t2 k subst
uTysX (SourceTy (ClassP c1 tys1)) (SourceTy (ClassP c2 tys2)) k subst
  | c1 == c2 = uTyListsX tys1 tys2 k subst
uTysX (SourceTy (NType tc1 tys1)) (SourceTy (NType tc2 tys2)) k subst
  | tc1 == tc2 = uTyListsX tys1 tys2 k subst

946
947
948
949
950
951
	-- Functions; just check the two parts
uTysX (FunTy fun1 arg1) (FunTy fun2 arg2) k subst
  = uTysX fun1 fun2 (uTysX arg1 arg2 k) subst

	-- Type constructors must match
uTysX (TyConApp con1 tys1) (TyConApp con2 tys2) k subst
sof's avatar
sof committed
952
  | (con1 == con2 && equalLength tys1 tys2)
953
954
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
  = uTyListsX tys1 tys2 k subst

	-- Applications need a bit of care!
	-- They can match FunTy and TyConApp, so use splitAppTy_maybe
	-- NB: we've already dealt with type variables and Notes,
	-- so if one type is an App the other one jolly well better be too
uTysX (AppTy s1 t1) ty2 k subst
  = case tcSplitAppTy_maybe ty2 of
      Just (s2, t2) -> uTysX s1 s2 (uTysX t1 t2 k) subst
      Nothing       -> Nothing    -- Fail

uTysX ty1 (AppTy s2 t2) k subst
  = case tcSplitAppTy_maybe ty1 of
      Just (s1, t1) -> uTysX s1 s2 (uTysX t1 t2 k) subst
      Nothing       -> Nothing    -- Fail

	-- Not expecting for-alls in unification
#ifdef DEBUG
uTysX (ForAllTy _ _) ty2 k subst = panic "Unify.uTysX subst:ForAllTy (1st arg)"
uTysX ty1 (ForAllTy _ _) k subst = panic "Unify.uTysX subst:ForAllTy (2nd arg)"
#endif

	-- Anything else fails
uTysX ty1 ty2 k subst = Nothing


uTyListsX []         []         k subst = k subst
uTyListsX (ty1:tys1) (ty2:tys2) k subst = uTysX ty1 ty2 (uTyListsX tys1 tys2 k) subst
uTyListsX tys1	     tys2       k subst = Nothing   -- Fail if the lists are different lengths
982
\end{code}
983

984
\begin{code}
985
986
987
988
989
990
991
992
993
994
995
996
997
-- Invariant: tv1 is a unifiable variable
uVarX tv1 ty2 k subst@(tmpls, env)
  = case lookupSubstEnv env tv1 of
      Just (DoneTy ty1) ->    -- Already bound
		     uTysX ty1 ty2 k subst

      Nothing	     -- Not already bound
	       |  typeKind ty2 `eqKind` tyVarKind tv1
	       && occur_check_ok ty2
	       ->     -- No kind mismatch nor occur check
                  k (tmpls, extendSubstEnv env tv1 (DoneTy ty2))

	       | otherwise -> Nothing	-- Fail if kind mis-match or occur check
998
  where
999
1000
    occur_check_ok ty = all occur_check_ok_tv (varSetElems (tyVarsOfType ty))
    occur_check_ok_tv tv | tv1 == tv = False