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

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

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

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

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

24
  --------------------------------
25
  -- MetaDetails
26
  UserTypeCtxt(..), pprUserTypeCtxt,
27
28
29
30
  TcTyVarDetails(..), pprTcTyVarDetails,
  MetaDetails(Flexi, Indirect), MetaInfo(..), 
  SkolemInfo(..), pprSkolTvBinding, pprSkolInfo,
  isImmutableTyVar, isSkolemTyVar, isMetaTyVar,  isMetaTyVarTy,
31
  isSigTyVar, isExistentialTyVar,  isTyConableTyVar,
32
  metaTvRef, 
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
33
  isFlexi, isIndirect, isUnkSkol, isRuntimeUnkSkol,
34
35

  --------------------------------
36
  -- Builders
37
  mkPhiTy, mkSigmaTy, 
38

39
40
41
  --------------------------------
  -- Splitters  
  -- These are important because they do not look through newtypes
42
  tcView,
43
  tcSplitForAllTys, tcSplitPhiTy, tcSplitPredFunTy_maybe,
44
  tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy, tcSplitFunTysN,
45
  tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
46
  tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, repSplitAppTy_maybe,
47
48
  tcInstHeadTyNotSynonym, tcInstHeadTyAppAllTyVars,
  tcGetTyVar_maybe, tcGetTyVar,
49
  tcSplitSigmaTy, tcDeepSplitSigmaTy_maybe, 
50
51
52
53

  ---------------------------------
  -- Predicates. 
  -- Again, newtypes are opaque
54
  tcEqType, tcEqTypes, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred, tcEqTypeX,
55
  eqKind, 
56
  isSigmaTy, isOverloadedTy, isRigidTy, 
Ian Lynagh's avatar
Ian Lynagh committed
57
  isDoubleTy, isFloatTy, isIntTy, isWordTy, isStringTy,
58
  isIntegerTy, isBoolTy, isUnitTy, isCharTy,
59
  isTauTy, isTauTyCon, tcIsTyVarTy, tcIsForAllTy, 
60
  isSynFamilyTyConApp,
61
62
63

  ---------------------------------
  -- Misc type manipulators
64
  deNoteType,
65
  tyClsNamesOfType, tyClsNamesOfDFunHead, 
66
67
68
69
  getDFunTyKey,

  ---------------------------------
  -- Predicate types  
70
  getClassPredTys_maybe, getClassPredTys, 
71
  isClassPred, isTyVarClassPred, isEqPred, 
72
73
  mkClassPred, mkIPPred, tcSplitPredTy_maybe, 
  mkDictTy, evVarPred,
74
75
  isPredTy, isDictTy, isDictLikeTy,
  tcSplitDFunTy, tcSplitDFunHead, predTyUnique, 
76
  isIPPred, 
77
  isRefineableTy, isRefineablePred,
78

79
80
81
82
83
84
85
86
  -- * Tidying type related things up for printing
  tidyType,      tidyTypes,
  tidyOpenType,  tidyOpenTypes,
  tidyTyVarBndr, tidyFreeTyVars,
  tidyOpenTyVar, tidyOpenTyVars,
  tidyTopType,   tidyPred,
  tidyKind, tidySkolemTyVar,

87
88
89
90
91
92
93
94
  ---------------------------------
  -- 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
95
96
  isFFIPrimArgumentTy, -- :: DynFlags -> Type -> Bool
  isFFIPrimResultTy,   -- :: DynFlags -> Type -> Bool
97
  isFFILabelTy,        -- :: Type -> Bool
sof's avatar
sof committed
98
99
  isFFIDotnetTy,       -- :: DynFlags -> Type -> Bool
  isFFIDotnetObjTy,    -- :: Type -> Bool
100
  isFFITy,	       -- :: Type -> Bool
101
  isFunPtrTy,          -- :: Type -> Bool
102
  tcSplitIOType_maybe, -- :: Type -> Maybe Type  
103

104
105
106
107
  --------------------------------
  -- Rexported from Coercion
  typeKind,

108
109
  --------------------------------
  -- Rexported from Type
110
  Kind, 	-- Stuff to do with kinds is insensitive to pre/post Tc
111
  unliftedTypeKind, liftedTypeKind, argTypeKind,
Simon Marlow's avatar
Simon Marlow committed
112
  openTypeKind, mkArrowKind, mkArrowKinds, 
113
  isLiftedTypeKind, isUnliftedTypeKind, isSubOpenTypeKind, 
114
  isSubArgTypeKind, isSubKind, splitKindFunTys, defaultKind,
115
  kindVarRef, mkKindVar,  
116

117
  Type, PredType(..), ThetaType, 
118
119
  mkForAllTy, mkForAllTys, 
  mkFunTy, mkFunTys, zipFunTys, 
120
  mkTyConApp, mkAppTy, mkAppTys, applyTy, applyTys,
121
  mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys, 
122

123
124
  -- Type substitutions
  TvSubst(..), 	-- Representation visible to a few friends
125
  TvSubstEnv, emptyTvSubst, substEqSpec,
126
127
  mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, 
  mkTopTvSubst, notElemTvSubst, unionTvSubst,
128
129
  getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope, lookupTyVar,
  extendTvSubst, extendTvSubstList, isInScope, mkTvSubst, zipTyEnv,
130
  substTy, substTys, substTyWith, substTheta, substTyVar, substTyVars, substTyVarBndr,
131

132
133
  isUnLiftedType,	-- Source types are always lifted
  isUnboxedTupleType,	-- Ditto
134
  isPrimitiveType, 
135

136
  tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
137
138
  tcTyVarsOfType, tcTyVarsOfTypes, tcTyVarsOfPred, exactTyVarsOfType,
  exactTyVarsOfTypes, 
139

140
  pprKind, pprParendKind,
141
  pprType, pprParendType, pprTypeApp, pprTyThingCategory,
142
  pprPred, pprTheta, pprThetaArrow, pprClassPred
143

144
  ) where
145

146
#include "HsVersions.h"
147

148
-- friends:
149
150
151
152
153
import TypeRep
import DataCon
import Class
import Var
import ForeignCall
154
import VarSet
155
import Type
156
import Coercion
157
import TyCon
158
import HsExpr( HsMatchContext )
159
160

-- others:
161
162
import DynFlags
import Name
163
import NameSet
164
165
166
167
168
169
170
import VarEnv
import PrelNames
import TysWiredIn
import BasicTypes
import Util
import Maybes
import ListSetOps
171
import Outputable
172
import FastString
Simon Marlow's avatar
Simon Marlow committed
173

174
import Data.List( mapAccumL )
Simon Marlow's avatar
Simon Marlow committed
175
import Data.IORef
176
177
\end{code}

178
179
%************************************************************************
%*									*
180
181
182
183
\subsection{Types}
%*									*
%************************************************************************

184
185
186
The type checker divides the generic Type world into the 
following more structured beasts:

187
sigma ::= forall tyvars. phi
188
189
190
191
192
193
194
195
196
197
	-- 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

198
199
200
phi :: theta => rho

rho ::= sigma -> rho
201
202
203
204
205
206
207
208
209
210
211
212
     |  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.

213
\begin{code}
214
type TcTyVar = TyVar  	-- Used only during type inference
215
type TcCoVar = CoVar  	-- Used only during type inference; mutable
216
type TcType = Type 	-- A TcType can have mutable type variables
217
218
219
220
221
	-- 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

222
-- These types do not have boxy type variables in them
223
224
type TcPredType     = PredType
type TcThetaType    = ThetaType
225
type TcSigmaType    = TcType
226
type TcRhoType      = TcType
227
type TcTauType      = TcType
228
type TcKind         = Kind
229
type TcTyVarSet     = TyVarSet
230
231
232
233
234
235
\end{code}


%************************************************************************
%*									*
\subsection{TyVarDetails}
236
237
238
%*									*
%************************************************************************

239
240
TyVarDetails gives extra info about type variables, used during type
checking.  It's attached to mutable type variables only.
241
242
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.
243

244

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
Note [Signature skolems]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider this

  x :: [a]
  y :: b
  (x,y,z) = ([y,z], z, head x)

Here, x and y have type sigs, which go into the environment.  We used to
instantiate their types with skolem constants, and push those types into
the RHS, so we'd typecheck the RHS with type
	( [a*], b*, c )
where a*, b* are skolem constants, and c is an ordinary meta type varible.

The trouble is that the occurrences of z in the RHS force a* and b* to 
be the *same*, so we can't make them into skolem constants that don't unify
with each other.  Alas.

263
One solution would be insist that in the above defn the programmer uses
264
265
266
the same type variable in both type signatures.  But that takes explanation.

The alternative (currently implemented) is to have a special kind of skolem
267
268
269
270
constant, SigTv, which can unify with other SigTvs.  These are *not* treated
as righd for the purposes of GADTs.  And they are used *only* for pattern 
bindings and mutually recursive function bindings.  See the function
TcBinds.tcInstSig, and its use_skols parameter.
271
272


273
\begin{code}
274
275
-- A TyVarDetails is inside a TyVar
data TcTyVarDetails
276
  = SkolemTv SkolemInfo	  -- A skolem constant
277

278
279
280
  | FlatSkol TcType	  
           -- The "skolem" obtained by flattening during
    	   -- constraint simplification
281
    
282
283
284
285
           -- In comments we will use the notation alpha[flat = ty]
           -- to represent a flattening skolem variable alpha
           -- identified with type ty.
          
286
  | MetaTv MetaInfo (IORef MetaDetails)
287
288

data MetaDetails
289
  = Flexi  -- Flexi type variables unify to become Indirects  
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
  | Indirect TcType

data MetaInfo 
   = TauTv	   -- This MetaTv is an ordinary unification variable
     		   -- A TauTv is always filled in with a tau-type, which
		   -- never contains any ForAlls 

   | SigTv Name	   -- A variant of TauTv, except that it should not be
		   -- unified with a type, only with a type variable
		   -- SigTvs are only distinguished to improve error messages
		   --      see Note [Signature skolems]        
		   --      The MetaDetails, if filled in, will 
		   --      always be another SigTv or a SkolemTv
		   -- The Name is the name of the function from whose
		   -- type signature we got this skolem

306
307
308
309
310
   | TcsTv	   -- A MetaTv allocated by the constraint solver
     		   -- Its particular property is that it is always "touchable"
		   -- Nevertheless, the constraint solver has to try to guess
		   -- what type to instantiate it to

311
312
313
314
----------------------------------
-- SkolemInfo describes a site where 
--   a) type variables are skolemised
--   b) an implication constraint is generated
315
data SkolemInfo
316
317
318
319
320
  = SigSkol UserTypeCtxt	-- A skolem that is created by instantiating
				-- a programmer-supplied type signature
				-- Location of the binding site is on the TyVar

	-- The rest are for non-scoped skolems
321
  | ClsSkol Class	-- Bound at a class decl
322
323
  | InstSkol 		-- Bound at an instance decl
  | FamInstSkol 	-- Bound at a family instance decl
324
325
326
327
328
329
330
  | PatSkol 	        -- An existential type variable bound by a pattern for
      DataCon           -- a data constructor with an existential type.
      (HsMatchContext Name)	
	     --	e.g.   data T = forall a. Eq a => MkT a
	     --        f (MkT x) = ...
	     -- The pattern MkT x will allocate an existential type
	     -- variable for 'a'.  
331

332
333
334
  | ArrowSkol 	  	-- An arrow form (see TcArrows)

  | IPSkol [IPName Name]  -- Binding site of an implicit parameter
335

336
337
  | RuleSkol RuleName	-- The LHS of a RULE
  | GenSkol TcType	-- Bound when doing a subsumption check for ty
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
338

339
340
341
  | RuntimeUnkSkol      -- a type variable used to represent an unknown
                        -- runtime type (used in the GHCi debugger)

342
343
344
  | NoScSkol		-- Used for the "self" superclass when solving
    			-- superclasses; don't generate superclasses of me

345
346
347
348
349
  | UnkSkol		-- Unhelpful info (until I improve it)

-------------------------------------
-- UserTypeCtxt describes the places where a 
-- programmer-written type signature can occur
350
-- Like SkolemInfo, no location info
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
data UserTypeCtxt 
  = FunSigCtxt Name	-- Function type signature
			-- Also used for types in SPECIALISE pragmas
  | ExprSigCtxt		-- Expression type signature
  | ConArgCtxt Name	-- Data constructor argument
  | TySynCtxt Name	-- RHS of a type synonym decl
  | GenPatCtxt		-- Pattern in generic decl
			-- 	f{| a+b |} (Inl x) = ...
  | LamPatSigCtxt		-- Type sig in lambda pattern
			-- 	f (x::t) = ...
  | BindPatSigCtxt	-- Type sig in pattern binding pattern
			--	(x::t, y) = e
  | ResSigCtxt		-- Result type sig
			-- 	f x :: t = ....
  | ForSigCtxt Name	-- Foreign inport or export signature
  | DefaultDeclCtxt	-- Types in a default declaration
  | SpecInstCtxt	-- SPECIALISE instance pragma
368
  | ThBrackCtxt		-- Template Haskell type brackets [t| ... |]
369
370
371
372
373
374
375
376
377
378

-- Notes re TySynCtxt
-- We allow type synonyms that aren't types; e.g.  type List = []
--
-- If the RHS mentions tyvars that aren't in scope, we'll 
-- quantify over them:
--	e.g. 	type T = a->a
-- will become	type T = forall a. a->a
--
-- With gla-exts that's right, but for H98 we should complain. 
379
380
381
382
383
384
385
386
387

---------------------------------
-- Kind variables:

mkKindName :: Unique -> Name
mkKindName unique = mkSystemName unique kind_var_occ

kindVarRef :: KindVar -> IORef MetaDetails
kindVarRef tc = 
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
388
  ASSERT ( isTcTyVar tc )
389
390
  case tcTyVarDetails tc of
    MetaTv TauTv ref -> ref
Ian Lynagh's avatar
Ian Lynagh committed
391
    _                -> pprPanic "kindVarRef" (ppr tc)
392
393
394
395
396
397
398
399
400
401
402
403
404

mkKindVar :: Unique -> IORef MetaDetails -> KindVar
mkKindVar u r 
  = mkTcTyVar (mkKindName u)
              tySuperKind  -- not sure this is right,
                            -- do we need kind vars for
                            -- coercions?
              (MetaTv TauTv r)

kind_var_occ :: OccName	-- Just one for all KindVars
			-- They may be jiggled by tidying
kind_var_occ = mkOccName tvName "k"
\end{code}
405

406
407
408
409
410
%************************************************************************
%*									*
		Pretty-printing
%*									*
%************************************************************************
411

412
413
414
\begin{code}
pprTcTyVarDetails :: TcTyVarDetails -> SDoc
-- For debugging
Ian Lynagh's avatar
Ian Lynagh committed
415
pprTcTyVarDetails (SkolemTv _)         = ptext (sLit "sk")
416
pprTcTyVarDetails (FlatSkol {})        = ptext (sLit "fsk")
Ian Lynagh's avatar
Ian Lynagh committed
417
pprTcTyVarDetails (MetaTv TauTv _)     = ptext (sLit "tau")
418
pprTcTyVarDetails (MetaTv TcsTv _)     = ptext (sLit "tcs")
Ian Lynagh's avatar
Ian Lynagh committed
419
pprTcTyVarDetails (MetaTv (SigTv _) _) = ptext (sLit "sig")
420
421

pprUserTypeCtxt :: UserTypeCtxt -> SDoc
Ian Lynagh's avatar
Ian Lynagh committed
422
423
424
425
426
pprUserTypeCtxt (FunSigCtxt n)  = ptext (sLit "the type signature for") <+> quotes (ppr n)
pprUserTypeCtxt ExprSigCtxt     = ptext (sLit "an expression type signature")
pprUserTypeCtxt (ConArgCtxt c)  = ptext (sLit "the type of the constructor") <+> quotes (ppr c)
pprUserTypeCtxt (TySynCtxt c)   = ptext (sLit "the RHS of the type synonym") <+> quotes (ppr c)
pprUserTypeCtxt GenPatCtxt      = ptext (sLit "the type pattern of a generic definition")
427
pprUserTypeCtxt ThBrackCtxt     = ptext (sLit "a Template Haskell quotation [t|...|]")
Ian Lynagh's avatar
Ian Lynagh committed
428
429
430
431
432
433
pprUserTypeCtxt LamPatSigCtxt   = ptext (sLit "a pattern type signature")
pprUserTypeCtxt BindPatSigCtxt  = ptext (sLit "a pattern type signature")
pprUserTypeCtxt ResSigCtxt      = ptext (sLit "a result type signature")
pprUserTypeCtxt (ForSigCtxt n)  = ptext (sLit "the foreign declaration for") <+> quotes (ppr n)
pprUserTypeCtxt DefaultDeclCtxt = ptext (sLit "a type in a `default' declaration")
pprUserTypeCtxt SpecInstCtxt    = ptext (sLit "a SPECIALISE instance pragma")
434
435
436
437
438

pprSkolTvBinding :: TcTyVar -> SDoc
-- Print info about the binding of a skolem tyvar, 
-- or nothing if we don't have anything useful to say
pprSkolTvBinding tv
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
439
  = ASSERT ( isTcTyVar tv )
440
    quotes (ppr tv) <+> ppr_details (tcTyVarDetails tv)
441
  where
442
    ppr_details (SkolemTv info)      = ppr_skol info
443
    ppr_details (FlatSkol {}) 	     = ptext (sLit "is a flattening type variable")
444
445
446
    ppr_details (MetaTv (SigTv n) _) = ptext (sLit "is bound by the type signature for")
                                       <+> quotes (ppr n)
    ppr_details (MetaTv _ _)         = ptext (sLit "is a meta type variable")
447

Ian Lynagh's avatar
Ian Lynagh committed
448
449
450
    ppr_skol UnkSkol	    = ptext (sLit "is an unknown type variable")	-- Unhelpful
    ppr_skol RuntimeUnkSkol = ptext (sLit "is an unknown runtime type")
    ppr_skol info           = sep [ptext (sLit "is a rigid type variable bound by"),
451
				   sep [pprSkolInfo info, 
452
					nest 2 (ptext (sLit "at") <+> ppr (getSrcLoc tv))]]
453
 
454
455
456
instance Outputable SkolemInfo where
  ppr = pprSkolInfo

457
pprSkolInfo :: SkolemInfo -> SDoc
458
459
460
461
462
463
464
465
466
467
468
469
470
471
-- Complete the sentence "is a rigid type variable bound by..."
pprSkolInfo (SigSkol ctxt)  = pprUserTypeCtxt ctxt
pprSkolInfo (IPSkol ips)    = ptext (sLit "the implicit-parameter bindings for")
                              <+> pprWithCommas ppr ips
pprSkolInfo (ClsSkol cls)   = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
pprSkolInfo InstSkol        = ptext (sLit "the instance declaration")
pprSkolInfo NoScSkol        = ptext (sLit "the instance declaration (self)")
pprSkolInfo FamInstSkol     = ptext (sLit "the family instance declaration")
pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
pprSkolInfo ArrowSkol       = ptext (sLit "the arrow form")
pprSkolInfo (PatSkol dc _)  = sep [ ptext (sLit "a pattern with constructor")
                                    , ppr dc <+> dcolon <+> ppr (dataConUserType dc) ]
pprSkolInfo (GenSkol ty)    = sep [ ptext (sLit "the polymorphic type")
			    	  , quotes (ppr ty) ]
472
473

-- UnkSkol
474
475
-- For type variables the others are dealt with by pprSkolTvBinding.  
-- For Insts, these cases should not happen
476
477
pprSkolInfo UnkSkol        = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
pprSkolInfo RuntimeUnkSkol = WARN( True, text "pprSkolInfo: RuntimeUnkSkol" ) ptext (sLit "RuntimeUnkSkol")
478
479

instance Outputable MetaDetails where
Ian Lynagh's avatar
Ian Lynagh committed
480
481
  ppr Flexi         = ptext (sLit "Flexi")
  ppr (Indirect ty) = ptext (sLit "Indirect") <+> ppr ty
482
483
\end{code}

484

485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
%************************************************************************
%*									*
\subsection{TidyType}
%*									*
%************************************************************************

\begin{code}
-- | This tidies up a type for printing in an error message, or in
-- an interface file.
-- 
-- It doesn't change the uniques at all, just the print names.
tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidyTyVarBndr env@(tidy_env, subst) tyvar
  = case tidyOccName tidy_env (getOccName name) of
      (tidy', occ') -> ((tidy', subst'), tyvar'')
	where
	  subst' = extendVarEnv subst tyvar tyvar''
	  tyvar' = setTyVarName tyvar name'
	  name'  = tidyNameOcc name occ'
		-- Don't forget to tidy the kind for coercions!
	  tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
		  | otherwise	  = tyvar'
	  kind'  = tidyType env (tyVarKind tyvar)
  where
    name = tyVarName tyvar

---------------
tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
-- ^ Add the free 'TyVar's to the env in tidy form,
-- so that we can tidy the type they are free in
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
-- using the environment if one has not already been allocated. See
-- also 'tidyTyVarBndr'
tidyOpenTyVar env@(_, subst) tyvar
  = case lookupVarEnv subst tyvar of
	Just tyvar' -> (env, tyvar')		-- Already substituted
	Nothing	    -> tidyTyVarBndr env tyvar	-- Treat it as a binder

---------------
tidyType :: TidyEnv -> Type -> Type
tidyType env@(_, subst) ty
  = go ty
  where
    go (TyVarTy tv)	    = case lookupVarEnv subst tv of
				Nothing  -> expand tv
				Just tv' -> expand tv'
    go (TyConApp tycon tys) = let args = map go tys
			      in args `seqList` TyConApp tycon args
    go (PredTy sty)	    = PredTy (tidyPred env sty)
    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)
			      where
			        (envp, tvp) = tidyTyVarBndr env tv

    -- Expand FlatSkols, the skolems introduced by flattening process
    -- We don't want to show them in type error messages
    expand tv | isTcTyVar tv
              , FlatSkol ty <- tcTyVarDetails tv
              = go ty
              | otherwise
              = TyVarTy tv

---------------
tidyTypes :: TidyEnv -> [Type] -> [Type]
tidyTypes env tys = map (tidyType env) tys

---------------
tidyPred :: TidyEnv -> PredType -> PredType
tidyPred env (IParam n ty)     = IParam n (tidyType env ty)
tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
tidyPred env (EqPred ty1 ty2)  = EqPred (tidyType env ty1) (tidyType env ty2)

---------------
-- | Grabs the free type variables, tidies them
-- and then uses 'tidyType' to work over the type itself
tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
tidyOpenType env ty
  = (env', tidyType env' ty)
  where
    env' = tidyFreeTyVars env (tyVarsOfType ty)

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

---------------
-- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
tidyTopType :: Type -> Type
tidyTopType ty = tidyType emptyTidyEnv ty

---------------
tidySkolemTyVar :: TidyEnv -> TcTyVar -> (TidyEnv, TcTyVar)
-- Tidy the type inside a GenSkol, preparatory to printing it
tidySkolemTyVar env tv
  = ASSERT( isTcTyVar tv && (isSkolemTyVar tv || isSigTyVar tv ) )
    (env1, mkTcTyVar (tyVarName tv) (tyVarKind tv) info1)
  where
    (env1, info1) = case tcTyVarDetails tv of
			SkolemTv info -> (env1, SkolemTv info')
				where
				  (env1, info') = tidy_skol_info env info
			info -> (env, info)

    tidy_skol_info env (GenSkol ty) = (env1, GenSkol ty1)
			    where
			      (env1, ty1)  = tidyOpenType env ty
    tidy_skol_info env info = (env, info)

---------------
tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
tidyKind env k = tidyOpenType env k
\end{code}


608
609
610
611
612
613
614
%************************************************************************
%*									*
		Predicates
%*									*
%************************************************************************

\begin{code}
615
616
isImmutableTyVar :: TyVar -> Bool

617
618
619
620
isImmutableTyVar tv
  | isTcTyVar tv = isSkolemTyVar tv
  | otherwise    = True

621
isTyConableTyVar, isSkolemTyVar, isExistentialTyVar, 
622
  isMetaTyVar :: TcTyVar -> Bool 
623
624

isTyConableTyVar tv	
625
	-- True of a meta-type variable that can be filled in 
626
627
628
629
	-- with a type constructor application; in particular,
	-- not a SigTv
  = ASSERT( isTcTyVar tv) 
    case tcTyVarDetails tv of
630
631
	MetaTv (SigTv _) _ -> False
	_                  -> True
632
	
633
isSkolemTyVar tv 
634
  = ASSERT2( isTcTyVar tv, ppr tv )
635
    case tcTyVarDetails tv of
636
637
638
	SkolemTv {} -> True
        FlatSkol {} -> True
 	MetaTv {}   -> False
639

640
641
642
isExistentialTyVar tv 	-- Existential type variable, bound by a pattern
  = ASSERT( isTcTyVar tv )
    case tcTyVarDetails tv of
643
	SkolemTv (PatSkol {}) -> True
Ian Lynagh's avatar
Ian Lynagh committed
644
	_                     -> False
645

646
isMetaTyVar tv 
647
  = ASSERT2( isTcTyVar tv, ppr tv )
648
    case tcTyVarDetails tv of
649
	MetaTv _ _ -> True
Ian Lynagh's avatar
Ian Lynagh committed
650
	_          -> False
651

652
653
654
isMetaTyVarTy :: TcType -> Bool
isMetaTyVarTy (TyVarTy tv) = isMetaTyVar tv
isMetaTyVarTy _            = False
655

Ian Lynagh's avatar
Ian Lynagh committed
656
isSigTyVar :: Var -> Bool
657
658
659
660
isSigTyVar tv 
  = ASSERT( isTcTyVar tv )
    case tcTyVarDetails tv of
	MetaTv (SigTv _) _ -> True
Ian Lynagh's avatar
Ian Lynagh committed
661
	_                  -> False
662

663
664
metaTvRef :: TyVar -> IORef MetaDetails
metaTvRef tv 
665
  = ASSERT2( isTcTyVar tv, ppr tv )
666
    case tcTyVarDetails tv of
667
	MetaTv _ ref -> ref
Ian Lynagh's avatar
Ian Lynagh committed
668
	_          -> pprPanic "metaTvRef" (ppr tv)
669
670

isFlexi, isIndirect :: MetaDetails -> Bool
Ian Lynagh's avatar
Ian Lynagh committed
671
672
isFlexi Flexi = True
isFlexi _     = False
673
674

isIndirect (Indirect _) = True
Ian Lynagh's avatar
Ian Lynagh committed
675
isIndirect _            = False
676

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
677
678
isRuntimeUnkSkol :: TyVar -> Bool
-- Called only in TcErrors; see Note [Runtime skolems] there
679
680
681
682
isRuntimeUnkSkol x | isTcTyVar x
  		   , SkolemTv RuntimeUnkSkol <- tcTyVarDetails x 
  		   = True
  		   | otherwise = False
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
683
684
685
686
687

isUnkSkol :: TyVar -> Bool
isUnkSkol x | isTcTyVar x
            , SkolemTv UnkSkol <- tcTyVarDetails x = True
            | otherwise = False
688
\end{code}
689

690
691
692
693
694
695
696
697

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

\begin{code}
698
mkSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
699
mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
sof's avatar
sof committed
700

701
mkPhiTy :: [PredType] -> Type -> Type
702
mkPhiTy theta ty = foldr (\p r -> mkFunTy (mkPredTy p) r) ty theta
703
704
\end{code}

705
@isTauTy@ tests for nested for-alls.  It should not be called on a boxy type.
sof's avatar
sof committed
706

707
\begin{code}
708
isTauTy :: Type -> Bool
709
isTauTy ty | Just ty' <- tcView ty = isTauTy ty'
710
isTauTy (TyVarTy _)	  = True
711
712
713
isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc
isTauTy (AppTy a b)	  = isTauTy a && isTauTy b
isTauTy (FunTy a b)	  = isTauTy a && isTauTy b
Ian Lynagh's avatar
Ian Lynagh committed
714
715
isTauTy (PredTy _)	  = True		-- Don't look through source types
isTauTy _    		  = False
716
717
718
719


isTauTyCon :: TyCon -> Bool
-- Returns False for type synonyms whose expansion is a polytype
720
isTauTyCon tc 
721
722
  | isClosedSynTyCon tc = isTauTy (snd (synTyConDefn tc))
  | otherwise           = True
723
724
725
726

---------------
isRigidTy :: TcType -> Bool
-- A type is rigid if it has no meta type variables in it
727
isRigidTy ty = all isImmutableTyVar (varSetElems (tcTyVarsOfType ty))
728

729
isRefineableTy :: TcType -> (Bool,Bool)
730
731
-- A type should have type refinements applied to it if it has
-- free type variables, and they are all rigid
732
isRefineableTy ty = (null tc_tvs,  all isImmutableTyVar tc_tvs)
733
734
735
		    where
		      tc_tvs = varSetElems (tcTyVarsOfType ty)

736
737
738
739
740
isRefineablePred :: TcPredType -> Bool
isRefineablePred pred = not (null tc_tvs) && all isImmutableTyVar tc_tvs
		      where
		        tc_tvs = varSetElems (tcTyVarsOfPred pred)

741
---------------
742
743
getDFunTyKey :: Type -> OccName	-- Get some string from a type, to be used to 
				-- construct a dictionary function name
744
getDFunTyKey ty | Just ty' <- tcView ty = getDFunTyKey ty'
745
746
747
getDFunTyKey (TyVarTy tv)    = getOccName tv
getDFunTyKey (TyConApp tc _) = getOccName tc
getDFunTyKey (AppTy fun _)   = getDFunTyKey fun
Ian Lynagh's avatar
Ian Lynagh committed
748
getDFunTyKey (FunTy _ _)     = getOccName funTyCon
749
750
751
getDFunTyKey (ForAllTy _ t)  = getDFunTyKey t
getDFunTyKey ty		     = pprPanic "getDFunTyKey" (pprType ty)
-- PredTy shouldn't happen
sof's avatar
sof committed
752
753
754
\end{code}


755
756
%************************************************************************
%*									*
757
\subsection{Expanding and splitting}
758
759
%*									*
%************************************************************************
760

761
762
763
764
765
766
767
These tcSplit functions are like their non-Tc analogues, but
	a) they do not look through newtypes
	b) they do not look through PredTys

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.

768
\begin{code}
769
770
771
tcSplitForAllTys :: Type -> ([TyVar], Type)
tcSplitForAllTys ty = split ty ty []
   where
772
     split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
Ian Lynagh's avatar
Ian Lynagh committed
773
     split _ (ForAllTy tv ty) tvs 
774
       | not (isCoVar tv) = split ty ty (tv:tvs)
Ian Lynagh's avatar
Ian Lynagh committed
775
     split orig_ty _ tvs = (reverse tvs, orig_ty)
776

Ian Lynagh's avatar
Ian Lynagh committed
777
tcIsForAllTy :: Type -> Bool
778
tcIsForAllTy ty | Just ty' <- tcView ty = tcIsForAllTy ty'
Ian Lynagh's avatar
Ian Lynagh committed
779
780
tcIsForAllTy (ForAllTy tv _) = not (isCoVar tv)
tcIsForAllTy _               = False
781

782
783
784
785
786
787
788
789
790
791
tcSplitPredFunTy_maybe :: Type -> Maybe (PredType, Type)
-- Split off the first predicate argument from a type
tcSplitPredFunTy_maybe ty | Just ty' <- tcView ty = tcSplitPredFunTy_maybe ty'
tcSplitPredFunTy_maybe (ForAllTy tv ty)
  | isCoVar tv = Just (coVarPred tv, ty)
tcSplitPredFunTy_maybe (FunTy arg res)
  | Just p <- tcSplitPredTy_maybe arg = Just (p, res)
tcSplitPredFunTy_maybe _
  = Nothing

792
tcSplitPhiTy :: Type -> (ThetaType, Type)
793
794
795
796
797
798
799
tcSplitPhiTy ty
  = split ty []
  where
    split ty ts 
      = case tcSplitPredFunTy_maybe ty of
	  Just (pred, ty) -> split ty (pred:ts)
	  Nothing         -> (reverse ts, ty)
800

801
tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
802
tcSplitSigmaTy ty = case tcSplitForAllTys ty of
803
			(tvs, rho) -> case tcSplitPhiTy rho of
804
805
					(theta, tau) -> (tvs, theta, tau)

806
-----------------------
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
tcDeepSplitSigmaTy_maybe
  :: TcSigmaType -> Maybe ([TcType], [TyVar], ThetaType, TcSigmaType)
-- Looks for a *non-trivial* quantified type, under zero or more function arrows
-- By "non-trivial" we mean either tyvars or constraints are non-empty

tcDeepSplitSigmaTy_maybe ty
  | Just (arg_ty, res_ty)           <- tcSplitFunTy_maybe ty
  , Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe res_ty
  = Just (arg_ty:arg_tys, tvs, theta, rho)

  | (tvs, theta, rho) <- tcSplitSigmaTy ty
  , not (null tvs && null theta)
  = Just ([], tvs, theta, rho)

  | otherwise = Nothing
822
823

-----------------------
824
tcTyConAppTyCon :: Type -> TyCon
825
826
827
tcTyConAppTyCon ty = case tcSplitTyConApp_maybe ty of
			Just (tc, _) -> tc
			Nothing	     -> pprPanic "tcTyConAppTyCon" (pprType ty)
828
829

tcTyConAppArgs :: Type -> [Type]
830
831
832
tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of
			Just (_, args) -> args
			Nothing	       -> pprPanic "tcTyConAppArgs" (pprType ty)
833
834
835
836
837
838
839

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])
840
tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty'
841
842
tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
tcSplitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
843
	-- Newtypes are opaque, so they may be split
844
845
	-- However, predicates are not treated
	-- as tycon applications by the type checker
Ian Lynagh's avatar
Ian Lynagh committed
846
tcSplitTyConApp_maybe _                 = Nothing
847

848
-----------------------
849
850
851
852
853
854
855
856
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)
857
858
tcSplitFunTy_maybe ty | Just ty' <- tcView ty           = tcSplitFunTy_maybe ty'
tcSplitFunTy_maybe (FunTy arg res) | not (isPredTy arg) = Just (arg, res)
Ian Lynagh's avatar
Ian Lynagh committed
859
tcSplitFunTy_maybe _                                    = Nothing
860
861
862
863
864
865
866
	-- Note the (not (isPredTy arg)) guard
	-- Consider	(?x::Int) => Bool
	-- We don't want to treat this as a function type!
	-- A concrete example is test tc230:
	--	f :: () -> (?p :: ()) => () -> ()
	--
	--	g = f () ()
867

868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
tcSplitFunTysN
	:: TcRhoType 
	-> Arity		-- N: Number of desired args
	-> ([TcSigmaType], 	-- Arg types (N or fewer)
	    TcSigmaType)	-- The rest of the type

tcSplitFunTysN ty n_args
  | n_args == 0
  = ([], ty)
  | Just (arg,res) <- tcSplitFunTy_maybe ty
  = case tcSplitFunTysN res (n_args - 1) of
	(args, res) -> (arg:args, res)
  | otherwise
  = ([], ty)

Ian Lynagh's avatar
Ian Lynagh committed
883
tcSplitFunTy :: Type -> (Type, Type)
884
tcSplitFunTy  ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
Ian Lynagh's avatar
Ian Lynagh committed
885
886

tcFunArgTy :: Type -> Type
887
tcFunArgTy    ty = fst (tcSplitFunTy ty)
Ian Lynagh's avatar
Ian Lynagh committed
888
889

tcFunResultTy :: Type -> Type
890
tcFunResultTy ty = snd (tcSplitFunTy ty)
891

892
-----------------------
893
tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
894
tcSplitAppTy_maybe ty | Just ty' <- tcView ty = tcSplitAppTy_maybe ty'
895
tcSplitAppTy_maybe ty = repSplitAppTy_maybe ty
896

897
tcSplitAppTy :: Type -> (Type, Type)
898
899
900
901
tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
		    Just stuff -> stuff
		    Nothing    -> pprPanic "tcSplitAppTy" (pprType ty)

902
903
904
905
906
907
908
909
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)

910
-----------------------
911
tcGetTyVar_maybe :: Type -> Maybe TyVar
912
tcGetTyVar_maybe ty | Just ty' <- tcView ty = tcGetTyVar_maybe ty'
Ian Lynagh's avatar
Ian Lynagh committed
913
914
tcGetTyVar_maybe (TyVarTy tv)   = Just tv
tcGetTyVar_maybe _              = Nothing
915
916
917
918
919
920
921

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

tcIsTyVarTy :: Type -> Bool
tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)

922
-----------------------
923
tcSplitDFunTy :: Type -> ([TyVar], Class, [Type])
924
-- Split the type of a dictionary function
925
926
927
-- We don't use tcSplitSigmaTy,  because a DFun may (with NDP)
-- have non-Pred arguments, such as
--     df :: forall m. (forall b. Eq b => Eq (m b)) -> C m
928
tcSplitDFunTy ty 
929
930
931
932
933
934
935
936
937
938
939
  = case tcSplitForAllTys ty                 of { (tvs, rho)  ->
    case tcSplitDFunHead (drop_pred_tys rho) of { (clas, tys) -> 
    (tvs, clas, tys) }}
  where
    -- Discard the context of the dfun.  This can be a mix of
    -- coercion and class constraints; or (in the general NDP case)
    -- some other function argument
    drop_pred_tys ty | Just ty' <- tcView ty = drop_pred_tys ty'
    drop_pred_tys (ForAllTy tv ty) = ASSERT( isCoVar tv ) drop_pred_tys ty
    drop_pred_tys (FunTy _ ty)     = drop_pred_tys ty
    drop_pred_tys ty               = ty
940
941
942
943
944

tcSplitDFunHead :: Type -> (Class, [Type])
tcSplitDFunHead tau  
  = case tcSplitPredTy_maybe tau of 
	Just (ClassP clas tys) -> (clas, tys)
945
	_ -> pprPanic "tcSplitDFunHead" (ppr tau)
946

947
tcInstHeadTyNotSynonym :: Type -> Bool
948
949
950
-- Used in Haskell-98 mode, for the argument types of an instance head
-- These must not be type synonyms, but everywhere else type synonyms
-- are transparent, so we need a special function here
951
tcInstHeadTyNotSynonym ty
952
  = case ty of
Ian Lynagh's avatar
Ian Lynagh committed
953
        TyConApp tc _ -> not (isSynTyCon tc)
Ian Lynagh's avatar
Ian Lynagh committed
954
        _ -> True
955
956
957
958
959
960
961

tcInstHeadTyAppAllTyVars :: Type -> Bool
-- Used in Haskell-98 mode, for the argument types of an instance head
-- These must be a constructor applied to type variable arguments
tcInstHeadTyAppAllTyVars ty
  = case ty of
	TyConApp _ tys  -> ok tys
962
	FunTy arg res   -> ok [arg, res]
Ian Lynagh's avatar
Ian Lynagh committed
963
	_               -> False
964
965
966
967
968
969
970
  where
	-- Check that all the types are type variables,
	-- and that each is distinct
    ok tys = equalLength tvs tys && hasNoDups tvs
	   where
	     tvs = mapCatMaybes get_tv tys

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
971
    get_tv (TyVarTy tv)  = Just tv	-- through synonyms
Ian Lynagh's avatar
Ian Lynagh committed
972
    get_tv _             = Nothing
973
974
\end{code}

975

976
977
978

%************************************************************************
%*									*
979
\subsection{Predicate types}
980
981
%*									*
%************************************************************************
982

983
\begin{code}
984
985
986
987
988
989
evVarPred :: EvVar -> PredType
evVarPred var
  = case tcSplitPredTy_maybe (varType var) of
      Just pred -> pred
      Nothing   -> pprPanic "evVarPred" (ppr var <+> ppr (varType var))

990
991
tcSplitPredTy_maybe :: Type -> Maybe PredType
   -- Returns Just for predicates only
992
tcSplitPredTy_maybe ty | Just ty' <- tcView ty = tcSplitPredTy_maybe ty'
993
tcSplitPredTy_maybe (PredTy p)    = Just p
Ian Lynagh's avatar
Ian Lynagh committed
994
995
tcSplitPredTy_maybe _             = Nothing

996
predTyUnique :: PredType -> Unique
Ian Lynagh's avatar
Ian Lynagh committed
997
998
999
predTyUnique (IParam n _)    = getUnique (ipNameName n)
predTyUnique (ClassP clas _) = getUnique clas
predTyUnique (EqPred a b)    = pprPanic "predTyUnique" (ppr (EqPred a b))
1000
1001
\end{code}

1002
1003

--------------------- Dictionary types ---------------------------------
1004
1005

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
1006
mkClassPred :: Class -> [Type] -> PredType
1007
mkClassPred clas tys = ClassP clas tys
1008

1009
isClassPred :: PredType -> Bool
Ian Lynagh's avatar
Ian Lynagh committed
1010
1011
isClassPred (ClassP _ _) = True
isClassPred _            = False
1012

Ian Lynagh's avatar
Ian Lynagh committed
1013
1014
1015
isTyVarClassPred :: PredType -> Bool
isTyVarClassPred (ClassP _ tys) = all tcIsTyVarTy tys
isTyVarClassPred _              = False
1016

1017
getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
1018
getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
Ian Lynagh's avatar
Ian Lynagh committed
1019
getClassPredTys_maybe _                 = Nothing
1020
1021
1022

getClassPredTys :: PredType -> (Class, [Type])
getClassPredTys (ClassP clas tys) = (clas, tys)
Ian Lynagh's avatar
Ian Lynagh committed
1023
getClassPredTys _ = panic "getClassPredTys"
1024
1025

mkDictTy :: Class -> [Type] -> Type
1026
mkDictTy clas tys = mkPredTy (ClassP clas tys)
1027

1028
1029
1030
1031
1032
1033
1034
isDictLikeTy :: Type -> Bool
-- Note [Dictionary-like types]
isDictLikeTy ty | Just ty' <- tcView ty = isDictTy ty'
isDictLikeTy (PredTy p) = isClassPred p
isDictLikeTy (TyConApp tc tys) 
  | isTupleTyCon tc     = all isDictLikeTy tys
isDictLikeTy _          = False
1035
\end{code}
1036

1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
Note [Dictionary-like types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Being "dictionary-like" means either a dictionary type or a tuple thereof.
In GHC 6.10 we build implication constraints which construct such tuples,
and if we land up with a binding
    t :: (C [a], Eq [a])
    t = blah
then we want to treat t as cheap under "-fdicts-cheap" for example.
(Implication constraints are normally inlined, but sadly not if the
occurrence is itself inside an INLINE function!  Until we revise the 
handling of implication constraints, that is.)  This turned out to
be important in getting good arities in DPH code.  Example:

    class C a
    class D a where { foo :: a -> a }
    instance C a => D (Maybe a) where { foo x = x }

    bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
    {-# INLINE bar #-}
    bar x y = (foo (Just x), foo (Just y))

Then 'bar' should jolly well have arity 4 (two dicts, two args), but
we ended up with something like
   bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
                                in \x,y. <blah>)

This is all a bit ad-hoc; eg it relies on knowing that implication
constraints build tuples.

1066
1067
1068
--------------------- Implicit parameters ---------------------------------

\begin{code}
1069
1070
1071
mkIPPred :: IPName Name -> Type -> PredType
mkIPPred ip ty = IParam ip ty

1072
isIPPred :: PredType -> Bool
1073
isIPPred (IParam _ _) = True
Ian Lynagh's avatar
Ian Lynagh committed
1074
isIPPred _            = False
1075
\end{code}
1076

1077
1078
1079
1080
1081
1082
1083
--------------------- Equality predicates ---------------------------------
\begin{code}
substEqSpec :: TvSubst -> [(TyVar,Type)] -> [(TcType,TcType)]
substEqSpec subst eq_spec = [ (substTyVar subst tv, substTy subst ty)
			    | (tv,ty) <- eq_spec]
\end{code}

1084

1085
1086
1087
1088
1089
%************************************************************************
%*									*
\subsection{Predicates}
%*									*
%************************************************************************
1090

1091
isSigmaTy returns true of any qualified type.  It doesn't *necessarily* have 
1092
1093
any foralls.  E.g.
	f :: (?x::Int) => Int -> Int
1094

1095
\begin{code}
1096
isSigmaTy :: Type -> Bool
1097
isSigmaTy ty | Just ty' <- tcView ty = isSigmaTy ty'
Ian Lynagh's avatar
Ian Lynagh committed
1098
1099
1100
isSigmaTy (ForAllTy _ _) = True
isSigmaTy (FunTy a _)    = isPredTy a
isSigmaTy _              = False
1101
1102

isOverloadedTy :: Type -> Bool
1103
-- Yes for a type of a function that might require evidence-passing
1104
-- Used only by bindLocalMethods
1105
-- NB: be sure to check for type with an equality predicate; hence isCoVar
1106
isOverloadedTy ty | Just ty' <- tcView ty = isOverloadedTy ty'
1107
1108
1109
isOverloadedTy (ForAllTy tv ty) = isCoVar tv || isOverloadedTy ty
isOverloadedTy (FunTy a _)      = isPredTy a
isOverloadedTy _                = False
1110
1111
1112

isPredTy :: Type -> Bool	-- Belongs in TcType because it does 
				-- not look through newtypes, or predtypes (of course)
1113
isPredTy ty | Just ty' <- tcView ty = isPredTy ty'
Ian Lynagh's avatar
Ian Lynagh committed
1114
1115
isPredTy (PredTy _) = True
isPredTy _          = False
1116
\end{code}
1117
1118

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
1119
1120
isFloatTy, isDoubleTy, isIntegerTy, isIntTy, isWordTy, isBoolTy,
    isUnitTy, isCharTy :: Type -> Bool
1121
1122
1123
1124
isFloatTy      = is_tc floatTyConKey
isDoubleTy     = is_tc doubleTyConKey
isIntegerTy    = is_tc integerTyConKey
isIntTy        = is_tc intTyConKey
Ian Lynagh's avatar
Ian Lynagh committed
1125
isWordTy       = is_tc wordTyConKey
1126
isBoolTy       = is_tc boolTyConKey
1127
isUnitTy       = is_tc unitTyConKey
1128
1129
isCharTy       = is_tc charTyConKey

Ian Lynagh's avatar
Ian Lynagh committed
1130
isStringTy :: Type -> Bool
1131
1132
1133
isStringTy ty
  = case tcSplitTyConApp_maybe ty of
      Just (tc, [arg_ty]) -> tc == listTyCon && isCharTy arg_ty
Ian Lynagh's avatar
Ian Lynagh committed
1134
      _                   -> False
1135
1136
1137
1138
1139
1140
1141

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

1143
1144
1145
1146
\begin{code}
-- NB: Currently used in places where we have already expanded type synonyms;
--     hence no 'coreView'.  This could, however, be changed without breaking
--     any code.
1147
1148
isSynFamilyTyConApp :: TcTauType -> Bool
isSynFamilyTyConApp (TyConApp tc tys) = isSynFamilyTyCon tc && 
1149
                                      length tys == tyConArity tc 
1150
isSynFamilyTyConApp _other            = False
1151
1152
\end{code}

1153

1154
1155
%************************************************************************
%*									*
1156
\subsection{Misc}
1157
1158
1159
1160
%*									*
%************************************************************************

\begin{code}
1161
1162
1163
1164
deNoteType :: Type -> Type
-- Remove all *outermost* type synonyms and other notes
deNoteType ty | Just ty' <- tcView ty = deNoteType ty'
deNoteType ty = ty
1165
1166
\end{code}

1167
1168
\begin{code}
tcTyVarsOfType :: Type -> TcTyVarSet
chak@cse.unsw.edu.au.'s avatar