Typechecker performance fixes and flatten skolem bugfixing
[ghc-hetmet.git] / compiler / typecheck / TcType.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[TcType]{Types used in the typechecker}
6
7 This module provides the Type interface for front-end parts of the 
8 compiler.  These parts 
9
10         * treat "source types" as opaque: 
11                 newtypes, and predicates are meaningful. 
12         * look through usage types
13
14 The "tc" prefix is for "TypeChecker", because the type checker
15 is the principal client.
16
17 \begin{code}
18 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   TcTyVarDetails(..), pprTcTyVarDetails,
28   MetaDetails(Flexi, Indirect), MetaInfo(..), 
29   SkolemInfo(..), pprSkolTvBinding, pprSkolInfo,
30   isImmutableTyVar, isSkolemTyVar, isMetaTyVar,  isMetaTyVarTy,
31   isSigTyVar, isExistentialTyVar,  isTyConableTyVar,
32   metaTvRef, 
33   isFlexi, isIndirect, isRuntimeUnk, isUnk,
34
35   --------------------------------
36   -- Builders
37   mkPhiTy, mkSigmaTy, 
38
39   --------------------------------
40   -- Splitters  
41   -- 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   tcInstHeadTyNotSynonym, tcInstHeadTyAppAllTyVars,
48   tcGetTyVar_maybe, tcGetTyVar,
49   tcSplitSigmaTy, tcDeepSplitSigmaTy_maybe, 
50
51   ---------------------------------
52   -- Predicates. 
53   -- Again, newtypes are opaque
54   tcEqType, tcEqTypes, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred, tcEqTypeX,
55   eqKind, 
56   isSigmaTy, isOverloadedTy, isRigidTy, 
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   getDFunTyKey,
67
68   ---------------------------------
69   -- Predicate types  
70   getClassPredTys_maybe, getClassPredTys, 
71   isClassPred, isTyVarClassPred, isEqPred, 
72   mkClassPred, mkIPPred, tcSplitPredTy_maybe, 
73   mkDictTy, evVarPred,
74   isPredTy, isDictTy, isDictLikeTy,
75   tcSplitDFunTy, tcSplitDFunHead, predTyUnique, 
76   isIPPred, 
77   isRefineableTy, isRefineablePred,
78
79   -- * Tidying type related things up for printing
80   tidyType,      tidyTypes,
81   tidyOpenType,  tidyOpenTypes,
82   tidyTyVarBndr, tidyFreeTyVars,
83   tidyOpenTyVar, tidyOpenTyVars,
84   tidyTopType,   tidyPred,
85   tidyKind, tidySkolemTyVar,
86
87   ---------------------------------
88   -- Foreign import and export
89   isFFIArgumentTy,     -- :: DynFlags -> Safety -> Type -> Bool
90   isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
91   isFFIExportResultTy, -- :: Type -> Bool
92   isFFIExternalTy,     -- :: Type -> Bool
93   isFFIDynArgumentTy,  -- :: Type -> Bool
94   isFFIDynResultTy,    -- :: Type -> Bool
95   isFFIPrimArgumentTy, -- :: DynFlags -> Type -> Bool
96   isFFIPrimResultTy,   -- :: DynFlags -> Type -> Bool
97   isFFILabelTy,        -- :: Type -> Bool
98   isFFIDotnetTy,       -- :: DynFlags -> Type -> Bool
99   isFFIDotnetObjTy,    -- :: Type -> Bool
100   isFFITy,             -- :: Type -> Bool
101   isFunPtrTy,          -- :: Type -> Bool
102   tcSplitIOType_maybe, -- :: Type -> Maybe Type  
103
104   --------------------------------
105   -- Rexported from Coercion
106   typeKind,
107
108   --------------------------------
109   -- Rexported from Type
110   Kind,         -- Stuff to do with kinds is insensitive to pre/post Tc
111   unliftedTypeKind, liftedTypeKind, argTypeKind,
112   openTypeKind, mkArrowKind, mkArrowKinds, 
113   isLiftedTypeKind, isUnliftedTypeKind, isSubOpenTypeKind, 
114   isSubArgTypeKind, isSubKind, splitKindFunTys, defaultKind,
115   kindVarRef, mkKindVar,  
116
117   Type, PredType(..), ThetaType, 
118   mkForAllTy, mkForAllTys, 
119   mkFunTy, mkFunTys, zipFunTys, 
120   mkTyConApp, mkAppTy, mkAppTys, applyTy, applyTys,
121   mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys, 
122
123   -- Type substitutions
124   TvSubst(..),  -- Representation visible to a few friends
125   TvSubstEnv, emptyTvSubst, substEqSpec,
126   mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
127   getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope, lookupTyVar,
128   extendTvSubst, extendTvSubstList, isInScope, mkTvSubst, zipTyEnv,
129   substTy, substTys, substTyWith, substTheta, substTyVar, substTyVars, substTyVarBndr,
130
131   isUnLiftedType,       -- Source types are always lifted
132   isUnboxedTupleType,   -- Ditto
133   isPrimitiveType, 
134
135   tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
136   tcTyVarsOfType, tcTyVarsOfTypes, tcTyVarsOfPred, exactTyVarsOfType,
137   exactTyVarsOfTypes, 
138
139   pprKind, pprParendKind,
140   pprType, pprParendType, pprTypeApp, pprTyThingCategory,
141   pprPred, pprTheta, pprThetaArrow, pprClassPred
142
143   ) where
144
145 #include "HsVersions.h"
146
147 -- friends:
148 import TypeRep
149 import DataCon
150 import Class
151 import Var
152 import ForeignCall
153 import VarSet
154 import Type
155 import Coercion
156 import TyCon
157 import HsExpr( HsMatchContext )
158
159 -- others:
160 import DynFlags
161 import Name
162 import NameSet
163 import VarEnv
164 import PrelNames
165 import TysWiredIn
166 import BasicTypes
167 import Util
168 import Maybes
169 import ListSetOps
170 import Outputable
171 import FastString
172
173 import Data.List( mapAccumL )
174 import Data.IORef
175 \end{code}
176
177 %************************************************************************
178 %*                                                                      *
179 \subsection{Types}
180 %*                                                                      *
181 %************************************************************************
182
183 The type checker divides the generic Type world into the 
184 following more structured beasts:
185
186 sigma ::= forall tyvars. phi
187         -- A sigma type is a qualified type
188         --
189         -- Note that even if 'tyvars' is empty, theta
190         -- may not be: e.g.   (?x::Int) => Int
191
192         -- Note that 'sigma' is in prenex form:
193         -- all the foralls are at the front.
194         -- A 'phi' type has no foralls to the right of
195         -- an arrow
196
197 phi :: theta => rho
198
199 rho ::= sigma -> rho
200      |  tau
201
202 -- A 'tau' type has no quantification anywhere
203 -- Note that the args of a type constructor must be taus
204 tau ::= tyvar
205      |  tycon tau_1 .. tau_n
206      |  tau_1 tau_2
207      |  tau_1 -> tau_2
208
209 -- In all cases, a (saturated) type synonym application is legal,
210 -- provided it expands to the required form.
211
212 \begin{code}
213 type TcTyVar = TyVar    -- Used only during type inference
214 type TcCoVar = CoVar    -- Used only during type inference; mutable
215 type TcType = Type      -- A TcType can have mutable type variables
216         -- Invariant on ForAllTy in TcTypes:
217         --      forall a. T
218         -- a cannot occur inside a MutTyVar in T; that is,
219         -- T is "flattened" before quantifying over a
220
221 -- These types do not have boxy type variables in them
222 type TcPredType     = PredType
223 type TcThetaType    = ThetaType
224 type TcSigmaType    = TcType
225 type TcRhoType      = TcType
226 type TcTauType      = TcType
227 type TcKind         = Kind
228 type TcTyVarSet     = TyVarSet
229 \end{code}
230
231
232 %************************************************************************
233 %*                                                                      *
234 \subsection{TyVarDetails}
235 %*                                                                      *
236 %************************************************************************
237
238 TyVarDetails gives extra info about type variables, used during type
239 checking.  It's attached to mutable type variables only.
240 It's knot-tied back to Var.lhs.  There is no reason in principle
241 why Var.lhs shouldn't actually have the definition, but it "belongs" here.
242
243
244 Note [Signature skolems]
245 ~~~~~~~~~~~~~~~~~~~~~~~~
246 Consider this
247
248   x :: [a]
249   y :: b
250   (x,y,z) = ([y,z], z, head x)
251
252 Here, x and y have type sigs, which go into the environment.  We used to
253 instantiate their types with skolem constants, and push those types into
254 the RHS, so we'd typecheck the RHS with type
255         ( [a*], b*, c )
256 where a*, b* are skolem constants, and c is an ordinary meta type varible.
257
258 The trouble is that the occurrences of z in the RHS force a* and b* to 
259 be the *same*, so we can't make them into skolem constants that don't unify
260 with each other.  Alas.
261
262 One solution would be insist that in the above defn the programmer uses
263 the same type variable in both type signatures.  But that takes explanation.
264
265 The alternative (currently implemented) is to have a special kind of skolem
266 constant, SigTv, which can unify with other SigTvs.  These are *not* treated
267 as righd for the purposes of GADTs.  And they are used *only* for pattern 
268 bindings and mutually recursive function bindings.  See the function
269 TcBinds.tcInstSig, and its use_skols parameter.
270
271
272 \begin{code}
273 -- A TyVarDetails is inside a TyVar
274 data TcTyVarDetails
275   = SkolemTv SkolemInfo   -- A skolem constant
276
277   | FlatSkol TcType       
278            -- The "skolem" obtained by flattening during
279            -- constraint simplification
280     
281            -- In comments we will use the notation alpha[flat = ty]
282            -- to represent a flattening skolem variable alpha
283            -- identified with type ty.
284           
285   | MetaTv MetaInfo (IORef MetaDetails)
286
287 data MetaDetails
288   = Flexi  -- Flexi type variables unify to become Indirects  
289   | Indirect TcType
290
291 data MetaInfo 
292    = TauTv         -- This MetaTv is an ordinary unification variable
293                    -- A TauTv is always filled in with a tau-type, which
294                    -- never contains any ForAlls 
295
296    | SigTv Name    -- A variant of TauTv, except that it should not be
297                    -- unified with a type, only with a type variable
298                    -- SigTvs are only distinguished to improve error messages
299                    --      see Note [Signature skolems]        
300                    --      The MetaDetails, if filled in, will 
301                    --      always be another SigTv or a SkolemTv
302                    -- The Name is the name of the function from whose
303                    -- type signature we got this skolem
304
305 ----------------------------------
306 -- SkolemInfo describes a site where 
307 --   a) type variables are skolemised
308 --   b) an implication constraint is generated
309 data SkolemInfo
310   = SigSkol UserTypeCtxt        -- A skolem that is created by instantiating
311                                 -- a programmer-supplied type signature
312                                 -- Location of the binding site is on the TyVar
313
314         -- The rest are for non-scoped skolems
315   | ClsSkol Class       -- Bound at a class decl
316   | InstSkol            -- Bound at an instance decl
317   | FamInstSkol         -- Bound at a family instance decl
318   | PatSkol             -- An existential type variable bound by a pattern for
319       DataCon           -- a data constructor with an existential type.
320       (HsMatchContext Name)     
321              -- e.g.   data T = forall a. Eq a => MkT a
322              --        f (MkT x) = ...
323              -- The pattern MkT x will allocate an existential type
324              -- variable for 'a'.  
325
326   | ArrowSkol           -- An arrow form (see TcArrows)
327
328   | IPSkol [IPName Name]  -- Binding site of an implicit parameter
329
330   | RuleSkol RuleName   -- The LHS of a RULE
331   | GenSkol TcType      -- Bound when doing a subsumption check for ty
332   | RuntimeUnkSkol      -- a type variable used to represent an unknown
333                         -- runtime type (used in the GHCi debugger)
334
335   | NoScSkol            -- Used for the "self" superclass when solving
336                         -- superclasses; don't generate superclasses of me
337
338   | UnkSkol             -- Unhelpful info (until I improve it)
339
340 -------------------------------------
341 -- UserTypeCtxt describes the places where a 
342 -- programmer-written type signature can occur
343 -- Like SkolemInfo, no location info
344 data UserTypeCtxt 
345   = FunSigCtxt Name     -- Function type signature
346                         -- Also used for types in SPECIALISE pragmas
347   | ExprSigCtxt         -- Expression type signature
348   | ConArgCtxt Name     -- Data constructor argument
349   | TySynCtxt Name      -- RHS of a type synonym decl
350   | GenPatCtxt          -- Pattern in generic decl
351                         --      f{| a+b |} (Inl x) = ...
352   | LamPatSigCtxt               -- Type sig in lambda pattern
353                         --      f (x::t) = ...
354   | BindPatSigCtxt      -- Type sig in pattern binding pattern
355                         --      (x::t, y) = e
356   | ResSigCtxt          -- Result type sig
357                         --      f x :: t = ....
358   | ForSigCtxt Name     -- Foreign inport or export signature
359   | DefaultDeclCtxt     -- Types in a default declaration
360   | SpecInstCtxt        -- SPECIALISE instance pragma
361   | ThBrackCtxt         -- Template Haskell type brackets [t| ... |]
362
363 -- Notes re TySynCtxt
364 -- We allow type synonyms that aren't types; e.g.  type List = []
365 --
366 -- If the RHS mentions tyvars that aren't in scope, we'll 
367 -- quantify over them:
368 --      e.g.    type T = a->a
369 -- will become  type T = forall a. a->a
370 --
371 -- With gla-exts that's right, but for H98 we should complain. 
372
373 ---------------------------------
374 -- Kind variables:
375
376 mkKindName :: Unique -> Name
377 mkKindName unique = mkSystemName unique kind_var_occ
378
379 kindVarRef :: KindVar -> IORef MetaDetails
380 kindVarRef tc = 
381   ASSERT ( isTcTyVar tc )
382   case tcTyVarDetails tc of
383     MetaTv TauTv ref -> ref
384     _                -> pprPanic "kindVarRef" (ppr tc)
385
386 mkKindVar :: Unique -> IORef MetaDetails -> KindVar
387 mkKindVar u r 
388   = mkTcTyVar (mkKindName u)
389               tySuperKind  -- not sure this is right,
390                             -- do we need kind vars for
391                             -- coercions?
392               (MetaTv TauTv r)
393
394 kind_var_occ :: OccName -- Just one for all KindVars
395                         -- They may be jiggled by tidying
396 kind_var_occ = mkOccName tvName "k"
397 \end{code}
398
399 %************************************************************************
400 %*                                                                      *
401                 Pretty-printing
402 %*                                                                      *
403 %************************************************************************
404
405 \begin{code}
406 pprTcTyVarDetails :: TcTyVarDetails -> SDoc
407 -- For debugging
408 pprTcTyVarDetails (SkolemTv _)         = ptext (sLit "sk")
409 pprTcTyVarDetails (FlatSkol {})        = ptext (sLit "fsk")
410 pprTcTyVarDetails (MetaTv TauTv _)     = ptext (sLit "tau")
411 pprTcTyVarDetails (MetaTv (SigTv _) _) = ptext (sLit "sig")
412
413 pprUserTypeCtxt :: UserTypeCtxt -> SDoc
414 pprUserTypeCtxt (FunSigCtxt n)  = ptext (sLit "the type signature for") <+> quotes (ppr n)
415 pprUserTypeCtxt ExprSigCtxt     = ptext (sLit "an expression type signature")
416 pprUserTypeCtxt (ConArgCtxt c)  = ptext (sLit "the type of the constructor") <+> quotes (ppr c)
417 pprUserTypeCtxt (TySynCtxt c)   = ptext (sLit "the RHS of the type synonym") <+> quotes (ppr c)
418 pprUserTypeCtxt GenPatCtxt      = ptext (sLit "the type pattern of a generic definition")
419 pprUserTypeCtxt ThBrackCtxt     = ptext (sLit "a Template Haskell quotation [t|...|]")
420 pprUserTypeCtxt LamPatSigCtxt   = ptext (sLit "a pattern type signature")
421 pprUserTypeCtxt BindPatSigCtxt  = ptext (sLit "a pattern type signature")
422 pprUserTypeCtxt ResSigCtxt      = ptext (sLit "a result type signature")
423 pprUserTypeCtxt (ForSigCtxt n)  = ptext (sLit "the foreign declaration for") <+> quotes (ppr n)
424 pprUserTypeCtxt DefaultDeclCtxt = ptext (sLit "a type in a `default' declaration")
425 pprUserTypeCtxt SpecInstCtxt    = ptext (sLit "a SPECIALISE instance pragma")
426
427 pprSkolTvBinding :: TcTyVar -> SDoc
428 -- Print info about the binding of a skolem tyvar, 
429 -- or nothing if we don't have anything useful to say
430 pprSkolTvBinding tv
431   = ASSERT ( isTcTyVar tv )
432     quotes (ppr tv) <+> ppr_details (tcTyVarDetails tv)
433   where
434     ppr_details (SkolemTv info)      = ppr_skol info
435     ppr_details (FlatSkol {})        = ptext (sLit "is a flattening type variable")
436     ppr_details (MetaTv TauTv _)     = ptext (sLit "is a meta type variable")
437     ppr_details (MetaTv (SigTv n) _) = ptext (sLit "is bound by the type signature for") <+> quotes (ppr n)
438
439     ppr_skol UnkSkol        = ptext (sLit "is an unknown type variable")        -- Unhelpful
440     ppr_skol RuntimeUnkSkol = ptext (sLit "is an unknown runtime type")
441     ppr_skol info           = sep [ptext (sLit "is a rigid type variable bound by"),
442                                    sep [pprSkolInfo info, 
443                                         nest 2 (ptext (sLit "at") <+> ppr (getSrcLoc tv))]]
444  
445 pprSkolInfo :: SkolemInfo -> SDoc
446 -- Complete the sentence "is a rigid type variable bound by..."
447 pprSkolInfo (SigSkol ctxt)  = pprUserTypeCtxt ctxt
448 pprSkolInfo (IPSkol ips)    = ptext (sLit "the implicit-parameter bindings for")
449                               <+> pprWithCommas ppr ips
450 pprSkolInfo (ClsSkol cls)   = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
451 pprSkolInfo InstSkol        = ptext (sLit "the instance declaration")
452 pprSkolInfo NoScSkol        = ptext (sLit "the instance declaration (self)")
453 pprSkolInfo FamInstSkol     = ptext (sLit "the family instance declaration")
454 pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
455 pprSkolInfo ArrowSkol       = ptext (sLit "the arrow form")
456 pprSkolInfo (PatSkol dc _)  = sep [ ptext (sLit "a pattern with constructor")
457                                     , ppr dc <+> dcolon <+> ppr (dataConUserType dc) ]
458 pprSkolInfo (GenSkol ty)    = sep [ ptext (sLit "the polymorphic type")
459                                   , quotes (ppr ty) ]
460
461 -- UnkSkol
462 -- For type variables the others are dealt with by pprSkolTvBinding.  
463 -- For Insts, these cases should not happen
464 pprSkolInfo UnkSkol        = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
465 pprSkolInfo RuntimeUnkSkol = WARN( True, text "pprSkolInfo: RuntimeUnkSkol" ) ptext (sLit "RuntimeUnkSkol")
466
467 instance Outputable MetaDetails where
468   ppr Flexi         = ptext (sLit "Flexi")
469   ppr (Indirect ty) = ptext (sLit "Indirect") <+> ppr ty
470 \end{code}
471
472
473 %************************************************************************
474 %*                                                                      *
475 \subsection{TidyType}
476 %*                                                                      *
477 %************************************************************************
478
479 \begin{code}
480 -- | This tidies up a type for printing in an error message, or in
481 -- an interface file.
482 -- 
483 -- It doesn't change the uniques at all, just the print names.
484 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
485 tidyTyVarBndr env@(tidy_env, subst) tyvar
486   = case tidyOccName tidy_env (getOccName name) of
487       (tidy', occ') -> ((tidy', subst'), tyvar'')
488         where
489           subst' = extendVarEnv subst tyvar tyvar''
490           tyvar' = setTyVarName tyvar name'
491           name'  = tidyNameOcc name occ'
492                 -- Don't forget to tidy the kind for coercions!
493           tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
494                   | otherwise     = tyvar'
495           kind'  = tidyType env (tyVarKind tyvar)
496   where
497     name = tyVarName tyvar
498
499 ---------------
500 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
501 -- ^ Add the free 'TyVar's to the env in tidy form,
502 -- so that we can tidy the type they are free in
503 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
504
505 ---------------
506 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
507 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
508
509 ---------------
510 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
511 -- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
512 -- using the environment if one has not already been allocated. See
513 -- also 'tidyTyVarBndr'
514 tidyOpenTyVar env@(_, subst) tyvar
515   = case lookupVarEnv subst tyvar of
516         Just tyvar' -> (env, tyvar')            -- Already substituted
517         Nothing     -> tidyTyVarBndr env tyvar  -- Treat it as a binder
518
519 ---------------
520 tidyType :: TidyEnv -> Type -> Type
521 tidyType env@(_, subst) ty
522   = go ty
523   where
524     go (TyVarTy tv)         = case lookupVarEnv subst tv of
525                                 Nothing  -> expand tv
526                                 Just tv' -> expand tv'
527     go (TyConApp tycon tys) = let args = map go tys
528                               in args `seqList` TyConApp tycon args
529     go (PredTy sty)         = PredTy (tidyPred env sty)
530     go (AppTy fun arg)      = (AppTy $! (go fun)) $! (go arg)
531     go (FunTy fun arg)      = (FunTy $! (go fun)) $! (go arg)
532     go (ForAllTy tv ty)     = ForAllTy tvp $! (tidyType envp ty)
533                               where
534                                 (envp, tvp) = tidyTyVarBndr env tv
535
536     -- Expand FlatSkols, the skolems introduced by flattening process
537     -- We don't want to show them in type error messages
538     expand tv | isTcTyVar tv
539               , FlatSkol ty <- tcTyVarDetails tv
540               = go ty
541               | otherwise
542               = TyVarTy tv
543
544 ---------------
545 tidyTypes :: TidyEnv -> [Type] -> [Type]
546 tidyTypes env tys = map (tidyType env) tys
547
548 ---------------
549 tidyPred :: TidyEnv -> PredType -> PredType
550 tidyPred env (IParam n ty)     = IParam n (tidyType env ty)
551 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
552 tidyPred env (EqPred ty1 ty2)  = EqPred (tidyType env ty1) (tidyType env ty2)
553
554 ---------------
555 -- | Grabs the free type variables, tidies them
556 -- and then uses 'tidyType' to work over the type itself
557 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
558 tidyOpenType env ty
559   = (env', tidyType env' ty)
560   where
561     env' = tidyFreeTyVars env (tyVarsOfType ty)
562
563 ---------------
564 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
565 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
566
567 ---------------
568 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
569 tidyTopType :: Type -> Type
570 tidyTopType ty = tidyType emptyTidyEnv ty
571
572 ---------------
573 tidySkolemTyVar :: TidyEnv -> TcTyVar -> (TidyEnv, TcTyVar)
574 -- Tidy the type inside a GenSkol, preparatory to printing it
575 tidySkolemTyVar env tv
576   = ASSERT( isTcTyVar tv && (isSkolemTyVar tv || isSigTyVar tv ) )
577     (env1, mkTcTyVar (tyVarName tv) (tyVarKind tv) info1)
578   where
579     (env1, info1) = case tcTyVarDetails tv of
580                         SkolemTv info -> (env1, SkolemTv info')
581                                 where
582                                   (env1, info') = tidy_skol_info env info
583                         info -> (env, info)
584
585     tidy_skol_info env (GenSkol ty) = (env1, GenSkol ty1)
586                             where
587                               (env1, ty1)  = tidyOpenType env ty
588     tidy_skol_info env info = (env, info)
589
590 ---------------
591 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
592 tidyKind env k = tidyOpenType env k
593 \end{code}
594
595
596 %************************************************************************
597 %*                                                                      *
598                 Predicates
599 %*                                                                      *
600 %************************************************************************
601
602 \begin{code}
603 isImmutableTyVar :: TyVar -> Bool
604
605 isImmutableTyVar tv
606   | isTcTyVar tv = isSkolemTyVar tv
607   | otherwise    = True
608
609 isTyConableTyVar, isSkolemTyVar, isExistentialTyVar, 
610   isMetaTyVar :: TcTyVar -> Bool 
611
612 isTyConableTyVar tv     
613         -- True of a meta-type variable that can be filled in 
614         -- with a type constructor application; in particular,
615         -- not a SigTv
616   = ASSERT( isTcTyVar tv) 
617     case tcTyVarDetails tv of
618         MetaTv TauTv _ -> True
619         _              -> False
620         
621 isSkolemTyVar tv 
622   = ASSERT2( isTcTyVar tv, ppr tv )
623     case tcTyVarDetails tv of
624         SkolemTv {} -> True
625         FlatSkol {} -> True
626         MetaTv {}   -> False
627
628 isExistentialTyVar tv   -- Existential type variable, bound by a pattern
629   = ASSERT( isTcTyVar tv )
630     case tcTyVarDetails tv of
631         SkolemTv (PatSkol {}) -> True
632         _                     -> False
633
634 isMetaTyVar tv 
635   = ASSERT2( isTcTyVar tv, ppr tv )
636     case tcTyVarDetails tv of
637         MetaTv _ _ -> True
638         _          -> False
639
640 isMetaTyVarTy :: TcType -> Bool
641 isMetaTyVarTy (TyVarTy tv) = isMetaTyVar tv
642 isMetaTyVarTy _            = False
643
644 isSigTyVar :: Var -> Bool
645 isSigTyVar tv 
646   = ASSERT( isTcTyVar tv )
647     case tcTyVarDetails tv of
648         MetaTv (SigTv _) _ -> True
649         _                  -> False
650
651 metaTvRef :: TyVar -> IORef MetaDetails
652 metaTvRef tv 
653   = ASSERT2( isTcTyVar tv, ppr tv )
654     case tcTyVarDetails tv of
655         MetaTv _ ref -> ref
656         _          -> pprPanic "metaTvRef" (ppr tv)
657
658 isFlexi, isIndirect :: MetaDetails -> Bool
659 isFlexi Flexi = True
660 isFlexi _     = False
661
662 isIndirect (Indirect _) = True
663 isIndirect _            = False
664
665 isRuntimeUnk :: TyVar -> Bool
666 isRuntimeUnk x | isTcTyVar x
667                , SkolemTv RuntimeUnkSkol <- tcTyVarDetails x = True
668                | otherwise = False
669
670 isUnk :: TyVar -> Bool
671 isUnk x | isTcTyVar x
672         , SkolemTv UnkSkol <- tcTyVarDetails x = True
673         | otherwise = False
674 \end{code}
675
676
677 %************************************************************************
678 %*                                                                      *
679 \subsection{Tau, sigma and rho}
680 %*                                                                      *
681 %************************************************************************
682
683 \begin{code}
684 mkSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
685 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
686
687 mkPhiTy :: [PredType] -> Type -> Type
688 mkPhiTy theta ty = foldr (\p r -> mkFunTy (mkPredTy p) r) ty theta
689 \end{code}
690
691 @isTauTy@ tests for nested for-alls.  It should not be called on a boxy type.
692
693 \begin{code}
694 isTauTy :: Type -> Bool
695 isTauTy ty | Just ty' <- tcView ty = isTauTy ty'
696 isTauTy (TyVarTy _)       = True
697 isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc
698 isTauTy (AppTy a b)       = isTauTy a && isTauTy b
699 isTauTy (FunTy a b)       = isTauTy a && isTauTy b
700 isTauTy (PredTy _)        = True                -- Don't look through source types
701 isTauTy _                 = False
702
703
704 isTauTyCon :: TyCon -> Bool
705 -- Returns False for type synonyms whose expansion is a polytype
706 isTauTyCon tc 
707   | isClosedSynTyCon tc = isTauTy (snd (synTyConDefn tc))
708   | otherwise           = True
709
710 ---------------
711 isRigidTy :: TcType -> Bool
712 -- A type is rigid if it has no meta type variables in it
713 isRigidTy ty = all isImmutableTyVar (varSetElems (tcTyVarsOfType ty))
714
715 isRefineableTy :: TcType -> (Bool,Bool)
716 -- A type should have type refinements applied to it if it has
717 -- free type variables, and they are all rigid
718 isRefineableTy ty = (null tc_tvs,  all isImmutableTyVar tc_tvs)
719                     where
720                       tc_tvs = varSetElems (tcTyVarsOfType ty)
721
722 isRefineablePred :: TcPredType -> Bool
723 isRefineablePred pred = not (null tc_tvs) && all isImmutableTyVar tc_tvs
724                       where
725                         tc_tvs = varSetElems (tcTyVarsOfPred pred)
726
727 ---------------
728 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to 
729                                 -- construct a dictionary function name
730 getDFunTyKey ty | Just ty' <- tcView ty = getDFunTyKey ty'
731 getDFunTyKey (TyVarTy tv)    = getOccName tv
732 getDFunTyKey (TyConApp tc _) = getOccName tc
733 getDFunTyKey (AppTy fun _)   = getDFunTyKey fun
734 getDFunTyKey (FunTy _ _)     = getOccName funTyCon
735 getDFunTyKey (ForAllTy _ t)  = getDFunTyKey t
736 getDFunTyKey ty              = pprPanic "getDFunTyKey" (pprType ty)
737 -- PredTy shouldn't happen
738 \end{code}
739
740
741 %************************************************************************
742 %*                                                                      *
743 \subsection{Expanding and splitting}
744 %*                                                                      *
745 %************************************************************************
746
747 These tcSplit functions are like their non-Tc analogues, but
748         a) they do not look through newtypes
749         b) they do not look through PredTys
750
751 However, they are non-monadic and do not follow through mutable type
752 variables.  It's up to you to make sure this doesn't matter.
753
754 \begin{code}
755 tcSplitForAllTys :: Type -> ([TyVar], Type)
756 tcSplitForAllTys ty = split ty ty []
757    where
758      split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
759      split _ (ForAllTy tv ty) tvs 
760        | not (isCoVar tv) = split ty ty (tv:tvs)
761      split orig_ty _ tvs = (reverse tvs, orig_ty)
762
763 tcIsForAllTy :: Type -> Bool
764 tcIsForAllTy ty | Just ty' <- tcView ty = tcIsForAllTy ty'
765 tcIsForAllTy (ForAllTy tv _) = not (isCoVar tv)
766 tcIsForAllTy _               = False
767
768 tcSplitPredFunTy_maybe :: Type -> Maybe (PredType, Type)
769 -- Split off the first predicate argument from a type
770 tcSplitPredFunTy_maybe ty | Just ty' <- tcView ty = tcSplitPredFunTy_maybe ty'
771 tcSplitPredFunTy_maybe (ForAllTy tv ty)
772   | isCoVar tv = Just (coVarPred tv, ty)
773 tcSplitPredFunTy_maybe (FunTy arg res)
774   | Just p <- tcSplitPredTy_maybe arg = Just (p, res)
775 tcSplitPredFunTy_maybe _
776   = Nothing
777
778 tcSplitPhiTy :: Type -> (ThetaType, Type)
779 tcSplitPhiTy ty
780   = split ty []
781   where
782     split ty ts 
783       = case tcSplitPredFunTy_maybe ty of
784           Just (pred, ty) -> split ty (pred:ts)
785           Nothing         -> (reverse ts, ty)
786
787 tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
788 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
789                         (tvs, rho) -> case tcSplitPhiTy rho of
790                                         (theta, tau) -> (tvs, theta, tau)
791
792 -----------------------
793 tcDeepSplitSigmaTy_maybe
794   :: TcSigmaType -> Maybe ([TcType], [TyVar], ThetaType, TcSigmaType)
795 -- Looks for a *non-trivial* quantified type, under zero or more function arrows
796 -- By "non-trivial" we mean either tyvars or constraints are non-empty
797
798 tcDeepSplitSigmaTy_maybe ty
799   | Just (arg_ty, res_ty)           <- tcSplitFunTy_maybe ty
800   , Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe res_ty
801   = Just (arg_ty:arg_tys, tvs, theta, rho)
802
803   | (tvs, theta, rho) <- tcSplitSigmaTy ty
804   , not (null tvs && null theta)
805   = Just ([], tvs, theta, rho)
806
807   | otherwise = Nothing
808
809 -----------------------
810 tcTyConAppTyCon :: Type -> TyCon
811 tcTyConAppTyCon ty = case tcSplitTyConApp_maybe ty of
812                         Just (tc, _) -> tc
813                         Nothing      -> pprPanic "tcTyConAppTyCon" (pprType ty)
814
815 tcTyConAppArgs :: Type -> [Type]
816 tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of
817                         Just (_, args) -> args
818                         Nothing        -> pprPanic "tcTyConAppArgs" (pprType ty)
819
820 tcSplitTyConApp :: Type -> (TyCon, [Type])
821 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
822                         Just stuff -> stuff
823                         Nothing    -> pprPanic "tcSplitTyConApp" (pprType ty)
824
825 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
826 tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty'
827 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
828 tcSplitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
829         -- Newtypes are opaque, so they may be split
830         -- However, predicates are not treated
831         -- as tycon applications by the type checker
832 tcSplitTyConApp_maybe _                 = Nothing
833
834 -----------------------
835 tcSplitFunTys :: Type -> ([Type], Type)
836 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
837                         Nothing        -> ([], ty)
838                         Just (arg,res) -> (arg:args, res')
839                                        where
840                                           (args,res') = tcSplitFunTys res
841
842 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
843 tcSplitFunTy_maybe ty | Just ty' <- tcView ty           = tcSplitFunTy_maybe ty'
844 tcSplitFunTy_maybe (FunTy arg res) | not (isPredTy arg) = Just (arg, res)
845 tcSplitFunTy_maybe _                                    = Nothing
846         -- Note the (not (isPredTy arg)) guard
847         -- Consider     (?x::Int) => Bool
848         -- We don't want to treat this as a function type!
849         -- A concrete example is test tc230:
850         --      f :: () -> (?p :: ()) => () -> ()
851         --
852         --      g = f () ()
853
854 tcSplitFunTysN
855         :: TcRhoType 
856         -> Arity                -- N: Number of desired args
857         -> ([TcSigmaType],      -- Arg types (N or fewer)
858             TcSigmaType)        -- The rest of the type
859
860 tcSplitFunTysN ty n_args
861   | n_args == 0
862   = ([], ty)
863   | Just (arg,res) <- tcSplitFunTy_maybe ty
864   = case tcSplitFunTysN res (n_args - 1) of
865         (args, res) -> (arg:args, res)
866   | otherwise
867   = ([], ty)
868
869 tcSplitFunTy :: Type -> (Type, Type)
870 tcSplitFunTy  ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
871
872 tcFunArgTy :: Type -> Type
873 tcFunArgTy    ty = fst (tcSplitFunTy ty)
874
875 tcFunResultTy :: Type -> Type
876 tcFunResultTy ty = snd (tcSplitFunTy ty)
877
878 -----------------------
879 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
880 tcSplitAppTy_maybe ty | Just ty' <- tcView ty = tcSplitAppTy_maybe ty'
881 tcSplitAppTy_maybe ty = repSplitAppTy_maybe ty
882
883 tcSplitAppTy :: Type -> (Type, Type)
884 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
885                     Just stuff -> stuff
886                     Nothing    -> pprPanic "tcSplitAppTy" (pprType ty)
887
888 tcSplitAppTys :: Type -> (Type, [Type])
889 tcSplitAppTys ty
890   = go ty []
891   where
892     go ty args = case tcSplitAppTy_maybe ty of
893                    Just (ty', arg) -> go ty' (arg:args)
894                    Nothing         -> (ty,args)
895
896 -----------------------
897 tcGetTyVar_maybe :: Type -> Maybe TyVar
898 tcGetTyVar_maybe ty | Just ty' <- tcView ty = tcGetTyVar_maybe ty'
899 tcGetTyVar_maybe (TyVarTy tv)   = Just tv
900 tcGetTyVar_maybe _              = Nothing
901
902 tcGetTyVar :: String -> Type -> TyVar
903 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
904
905 tcIsTyVarTy :: Type -> Bool
906 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
907
908 -----------------------
909 tcSplitDFunTy :: Type -> ([TyVar], Class, [Type])
910 -- Split the type of a dictionary function
911 -- We don't use tcSplitSigmaTy,  because a DFun may (with NDP)
912 -- have non-Pred arguments, such as
913 --     df :: forall m. (forall b. Eq b => Eq (m b)) -> C m
914 tcSplitDFunTy ty 
915   = case tcSplitForAllTys ty                 of { (tvs, rho)  ->
916     case tcSplitDFunHead (drop_pred_tys rho) of { (clas, tys) -> 
917     (tvs, clas, tys) }}
918   where
919     -- Discard the context of the dfun.  This can be a mix of
920     -- coercion and class constraints; or (in the general NDP case)
921     -- some other function argument
922     drop_pred_tys ty | Just ty' <- tcView ty = drop_pred_tys ty'
923     drop_pred_tys (ForAllTy tv ty) = ASSERT( isCoVar tv ) drop_pred_tys ty
924     drop_pred_tys (FunTy _ ty)     = drop_pred_tys ty
925     drop_pred_tys ty               = ty
926
927 tcSplitDFunHead :: Type -> (Class, [Type])
928 tcSplitDFunHead tau  
929   = case tcSplitPredTy_maybe tau of 
930         Just (ClassP clas tys) -> (clas, tys)
931         _ -> pprPanic "tcSplitDFunHead" (ppr tau)
932
933 tcInstHeadTyNotSynonym :: Type -> Bool
934 -- Used in Haskell-98 mode, for the argument types of an instance head
935 -- These must not be type synonyms, but everywhere else type synonyms
936 -- are transparent, so we need a special function here
937 tcInstHeadTyNotSynonym ty
938   = case ty of
939         TyConApp tc _ -> not (isSynTyCon tc)
940         _ -> True
941
942 tcInstHeadTyAppAllTyVars :: Type -> Bool
943 -- Used in Haskell-98 mode, for the argument types of an instance head
944 -- These must be a constructor applied to type variable arguments
945 tcInstHeadTyAppAllTyVars ty
946   = case ty of
947         TyConApp _ tys  -> ok tys
948         FunTy arg res   -> ok [arg, res]
949         _               -> False
950   where
951         -- Check that all the types are type variables,
952         -- and that each is distinct
953     ok tys = equalLength tvs tys && hasNoDups tvs
954            where
955              tvs = mapCatMaybes get_tv tys
956
957     get_tv (TyVarTy tv)  = Just tv      -- through synonyms
958     get_tv _             = Nothing
959 \end{code}
960
961
962
963 %************************************************************************
964 %*                                                                      *
965 \subsection{Predicate types}
966 %*                                                                      *
967 %************************************************************************
968
969 \begin{code}
970 evVarPred :: EvVar -> PredType
971 evVarPred var
972   = case tcSplitPredTy_maybe (varType var) of
973       Just pred -> pred
974       Nothing   -> pprPanic "evVarPred" (ppr var <+> ppr (varType var))
975
976 tcSplitPredTy_maybe :: Type -> Maybe PredType
977    -- Returns Just for predicates only
978 tcSplitPredTy_maybe ty | Just ty' <- tcView ty = tcSplitPredTy_maybe ty'
979 tcSplitPredTy_maybe (PredTy p)    = Just p
980 tcSplitPredTy_maybe _             = Nothing
981
982 predTyUnique :: PredType -> Unique
983 predTyUnique (IParam n _)    = getUnique (ipNameName n)
984 predTyUnique (ClassP clas _) = getUnique clas
985 predTyUnique (EqPred a b)    = pprPanic "predTyUnique" (ppr (EqPred a b))
986 \end{code}
987
988
989 --------------------- Dictionary types ---------------------------------
990
991 \begin{code}
992 mkClassPred :: Class -> [Type] -> PredType
993 mkClassPred clas tys = ClassP clas tys
994
995 isClassPred :: PredType -> Bool
996 isClassPred (ClassP _ _) = True
997 isClassPred _            = False
998
999 isTyVarClassPred :: PredType -> Bool
1000 isTyVarClassPred (ClassP _ tys) = all tcIsTyVarTy tys
1001 isTyVarClassPred _              = False
1002
1003 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
1004 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
1005 getClassPredTys_maybe _                 = Nothing
1006
1007 getClassPredTys :: PredType -> (Class, [Type])
1008 getClassPredTys (ClassP clas tys) = (clas, tys)
1009 getClassPredTys _ = panic "getClassPredTys"
1010
1011 mkDictTy :: Class -> [Type] -> Type
1012 mkDictTy clas tys = mkPredTy (ClassP clas tys)
1013
1014
1015
1016 isDictLikeTy :: Type -> Bool
1017 -- Note [Dictionary-like types]
1018 isDictLikeTy ty | Just ty' <- tcView ty = isDictTy ty'
1019 isDictLikeTy (PredTy p) = isClassPred p
1020 isDictLikeTy (TyConApp tc tys) 
1021   | isTupleTyCon tc     = all isDictLikeTy tys
1022 isDictLikeTy _          = False
1023 \end{code}
1024
1025 Note [Dictionary-like types]
1026 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1027 Being "dictionary-like" means either a dictionary type or a tuple thereof.
1028 In GHC 6.10 we build implication constraints which construct such tuples,
1029 and if we land up with a binding
1030     t :: (C [a], Eq [a])
1031     t = blah
1032 then we want to treat t as cheap under "-fdicts-cheap" for example.
1033 (Implication constraints are normally inlined, but sadly not if the
1034 occurrence is itself inside an INLINE function!  Until we revise the 
1035 handling of implication constraints, that is.)  This turned out to
1036 be important in getting good arities in DPH code.  Example:
1037
1038     class C a
1039     class D a where { foo :: a -> a }
1040     instance C a => D (Maybe a) where { foo x = x }
1041
1042     bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
1043     {-# INLINE bar #-}
1044     bar x y = (foo (Just x), foo (Just y))
1045
1046 Then 'bar' should jolly well have arity 4 (two dicts, two args), but
1047 we ended up with something like
1048    bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
1049                                 in \x,y. <blah>)
1050
1051 This is all a bit ad-hoc; eg it relies on knowing that implication
1052 constraints build tuples.
1053
1054 --------------------- Implicit parameters ---------------------------------
1055
1056 \begin{code}
1057 mkIPPred :: IPName Name -> Type -> PredType
1058 mkIPPred ip ty = IParam ip ty
1059
1060 isIPPred :: PredType -> Bool
1061 isIPPred (IParam _ _) = True
1062 isIPPred _            = False
1063 \end{code}
1064
1065 --------------------- Equality predicates ---------------------------------
1066 \begin{code}
1067 substEqSpec :: TvSubst -> [(TyVar,Type)] -> [(TcType,TcType)]
1068 substEqSpec subst eq_spec = [ (substTyVar subst tv, substTy subst ty)
1069                             | (tv,ty) <- eq_spec]
1070 \end{code}
1071
1072
1073 %************************************************************************
1074 %*                                                                      *
1075 \subsection{Predicates}
1076 %*                                                                      *
1077 %************************************************************************
1078
1079 isSigmaTy returns true of any qualified type.  It doesn't *necessarily* have 
1080 any foralls.  E.g.
1081         f :: (?x::Int) => Int -> Int
1082
1083 \begin{code}
1084 isSigmaTy :: Type -> Bool
1085 isSigmaTy ty | Just ty' <- tcView ty = isSigmaTy ty'
1086 isSigmaTy (ForAllTy _ _) = True
1087 isSigmaTy (FunTy a _)    = isPredTy a
1088 isSigmaTy _              = False
1089
1090 isOverloadedTy :: Type -> Bool
1091 -- Yes for a type of a function that might require evidence-passing
1092 -- Used only by bindLocalMethods
1093 -- NB: be sure to check for type with an equality predicate; hence isCoVar
1094 isOverloadedTy ty | Just ty' <- tcView ty = isOverloadedTy ty'
1095 isOverloadedTy (ForAllTy tv ty) = isCoVar tv || isOverloadedTy ty
1096 isOverloadedTy (FunTy a _)      = isPredTy a
1097 isOverloadedTy _                = False
1098
1099 isPredTy :: Type -> Bool        -- Belongs in TcType because it does 
1100                                 -- not look through newtypes, or predtypes (of course)
1101 isPredTy ty | Just ty' <- tcView ty = isPredTy ty'
1102 isPredTy (PredTy _) = True
1103 isPredTy _          = False
1104 \end{code}
1105
1106 \begin{code}
1107 isFloatTy, isDoubleTy, isIntegerTy, isIntTy, isWordTy, isBoolTy,
1108     isUnitTy, isCharTy :: Type -> Bool
1109 isFloatTy      = is_tc floatTyConKey
1110 isDoubleTy     = is_tc doubleTyConKey
1111 isIntegerTy    = is_tc integerTyConKey
1112 isIntTy        = is_tc intTyConKey
1113 isWordTy       = is_tc wordTyConKey
1114 isBoolTy       = is_tc boolTyConKey
1115 isUnitTy       = is_tc unitTyConKey
1116 isCharTy       = is_tc charTyConKey
1117
1118 isStringTy :: Type -> Bool
1119 isStringTy ty
1120   = case tcSplitTyConApp_maybe ty of
1121       Just (tc, [arg_ty]) -> tc == listTyCon && isCharTy arg_ty
1122       _                   -> False
1123
1124 is_tc :: Unique -> Type -> Bool
1125 -- Newtypes are opaque to this
1126 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
1127                         Just (tc, _) -> uniq == getUnique tc
1128                         Nothing      -> False
1129 \end{code}
1130
1131 \begin{code}
1132 -- NB: Currently used in places where we have already expanded type synonyms;
1133 --     hence no 'coreView'.  This could, however, be changed without breaking
1134 --     any code.
1135 isSynFamilyTyConApp :: TcTauType -> Bool
1136 isSynFamilyTyConApp (TyConApp tc tys) = isSynFamilyTyCon tc && 
1137                                       length tys == tyConArity tc 
1138 isSynFamilyTyConApp _other            = False
1139 \end{code}
1140
1141
1142 %************************************************************************
1143 %*                                                                      *
1144 \subsection{Misc}
1145 %*                                                                      *
1146 %************************************************************************
1147
1148 \begin{code}
1149 deNoteType :: Type -> Type
1150 -- Remove all *outermost* type synonyms and other notes
1151 deNoteType ty | Just ty' <- tcView ty = deNoteType ty'
1152 deNoteType ty = ty
1153 \end{code}
1154
1155 \begin{code}
1156 tcTyVarsOfType :: Type -> TcTyVarSet
1157 -- Just the *TcTyVars* free in the type
1158 -- (Types.tyVarsOfTypes finds all free TyVars)
1159 tcTyVarsOfType (TyVarTy tv)         = if isTcTyVar tv then unitVarSet tv
1160                                                       else emptyVarSet
1161 tcTyVarsOfType (TyConApp _ tys)     = tcTyVarsOfTypes tys
1162 tcTyVarsOfType (PredTy sty)         = tcTyVarsOfPred sty
1163 tcTyVarsOfType (FunTy arg res)      = tcTyVarsOfType arg `unionVarSet` tcTyVarsOfType res
1164 tcTyVarsOfType (AppTy fun arg)      = tcTyVarsOfType fun `unionVarSet` tcTyVarsOfType arg
1165 tcTyVarsOfType (ForAllTy tyvar ty)  = (tcTyVarsOfType ty `delVarSet` tyvar)
1166                                       `unionVarSet` tcTyVarsOfTyVar tyvar
1167         -- We do sometimes quantify over skolem TcTyVars
1168
1169 tcTyVarsOfTyVar :: TcTyVar -> TyVarSet
1170 tcTyVarsOfTyVar tv | isCoVar tv = tcTyVarsOfType (tyVarKind tv)
1171                    | otherwise  = emptyVarSet
1172
1173 tcTyVarsOfTypes :: [Type] -> TyVarSet
1174 tcTyVarsOfTypes tys = foldr (unionVarSet.tcTyVarsOfType) emptyVarSet tys
1175
1176 tcTyVarsOfPred :: PredType -> TyVarSet
1177 tcTyVarsOfPred (IParam _ ty)    = tcTyVarsOfType ty
1178 tcTyVarsOfPred (ClassP _ tys)   = tcTyVarsOfTypes tys
1179 tcTyVarsOfPred (EqPred ty1 ty2) = tcTyVarsOfType ty1 `unionVarSet` tcTyVarsOfType ty2
1180 \end{code}
1181
1182 Note [Silly type synonym]
1183 ~~~~~~~~~~~~~~~~~~~~~~~~~
1184 Consider
1185         type T a = Int
1186 What are the free tyvars of (T x)?  Empty, of course!  
1187 Here's the example that Ralf Laemmel showed me:
1188         foo :: (forall a. C u a -> C u a) -> u
1189         mappend :: Monoid u => u -> u -> u
1190
1191         bar :: Monoid u => u
1192         bar = foo (\t -> t `mappend` t)
1193 We have to generalise at the arg to f, and we don't
1194 want to capture the constraint (Monad (C u a)) because
1195 it appears to mention a.  Pretty silly, but it was useful to him.
1196
1197 exactTyVarsOfType is used by the type checker to figure out exactly
1198 which type variables are mentioned in a type.  It's also used in the
1199 smart-app checking code --- see TcExpr.tcIdApp
1200
1201 On the other hand, consider a *top-level* definition
1202         f = (\x -> x) :: T a -> T a
1203 If we don't abstract over 'a' it'll get fixed to GHC.Prim.Any, and then
1204 if we have an application like (f "x") we get a confusing error message 
1205 involving Any.  So the conclusion is this: when generalising
1206   - at top level use tyVarsOfType
1207   - in nested bindings use exactTyVarsOfType
1208 See Trac #1813 for example.
1209
1210 \begin{code}
1211 exactTyVarsOfType :: TcType -> TyVarSet
1212 -- Find the free type variables (of any kind)
1213 -- but *expand* type synonyms.  See Note [Silly type synonym] above.
1214 exactTyVarsOfType ty
1215   = go ty
1216   where
1217     go ty | Just ty' <- tcView ty = go ty'      -- This is the key line
1218     go (TyVarTy tv)               = unitVarSet tv
1219     go (TyConApp _ tys)           = exactTyVarsOfTypes tys
1220     go (PredTy ty)                = go_pred ty
1221     go (FunTy arg res)            = go arg `unionVarSet` go res
1222     go (AppTy fun arg)            = go fun `unionVarSet` go arg
1223     go (ForAllTy tyvar ty)        = delVarSet (go ty) tyvar
1224                                     `unionVarSet` go_tv tyvar
1225
1226     go_pred (IParam _ ty)    = go ty
1227     go_pred (ClassP _ tys)   = exactTyVarsOfTypes tys
1228     go_pred (EqPred ty1 ty2) = go ty1 `unionVarSet` go ty2
1229
1230     go_tv tyvar | isCoVar tyvar = go (tyVarKind tyvar)
1231                 | otherwise     = emptyVarSet
1232
1233 exactTyVarsOfTypes :: [TcType] -> TyVarSet
1234 exactTyVarsOfTypes tys = foldr (unionVarSet . exactTyVarsOfType) emptyVarSet tys
1235 \end{code}
1236
1237 Find the free tycons and classes of a type.  This is used in the front
1238 end of the compiler.
1239
1240 \begin{code}
1241 tyClsNamesOfType :: Type -> NameSet
1242 tyClsNamesOfType (TyVarTy _)                = emptyNameSet
1243 tyClsNamesOfType (TyConApp tycon tys)       = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
1244 tyClsNamesOfType (PredTy (IParam _ ty))     = tyClsNamesOfType ty
1245 tyClsNamesOfType (PredTy (ClassP cl tys))   = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
1246 tyClsNamesOfType (PredTy (EqPred ty1 ty2))  = tyClsNamesOfType ty1 `unionNameSets` tyClsNamesOfType ty2
1247 tyClsNamesOfType (FunTy arg res)            = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
1248 tyClsNamesOfType (AppTy fun arg)            = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
1249 tyClsNamesOfType (ForAllTy _ ty)            = tyClsNamesOfType ty
1250
1251 tyClsNamesOfTypes :: [Type] -> NameSet
1252 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
1253
1254 tyClsNamesOfDFunHead :: Type -> NameSet
1255 -- Find the free type constructors and classes 
1256 -- of the head of the dfun instance type
1257 -- The 'dfun_head_type' is because of
1258 --      instance Foo a => Baz T where ...
1259 -- The decl is an orphan if Baz and T are both not locally defined,
1260 --      even if Foo *is* locally defined
1261 tyClsNamesOfDFunHead dfun_ty 
1262   = case tcSplitSigmaTy dfun_ty of
1263         (_, _, head_ty) -> tyClsNamesOfType head_ty
1264 \end{code}
1265
1266
1267 %************************************************************************
1268 %*                                                                      *
1269 \subsection[TysWiredIn-ext-type]{External types}
1270 %*                                                                      *
1271 %************************************************************************
1272
1273 The compiler's foreign function interface supports the passing of a
1274 restricted set of types as arguments and results (the restricting factor
1275 being the )
1276
1277 \begin{code}
1278 tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type, CoercionI)
1279 -- (isIOType t) returns Just (IO,t',co)
1280 --                              if co : t ~ IO t'
1281 --              returns Nothing otherwise
1282 tcSplitIOType_maybe ty 
1283   = case tcSplitTyConApp_maybe ty of
1284         -- This split absolutely has to be a tcSplit, because we must
1285         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
1286
1287         Just (io_tycon, [io_res_ty]) 
1288            |  io_tycon `hasKey` ioTyConKey 
1289            -> Just (io_tycon, io_res_ty, IdCo ty)
1290
1291         Just (tc, tys)
1292            | not (isRecursiveTyCon tc)
1293            , Just (ty, co1) <- instNewTyCon_maybe tc tys
1294                   -- Newtypes that require a coercion are ok
1295            -> case tcSplitIOType_maybe ty of
1296                 Nothing             -> Nothing
1297                 Just (tc, ty', co2) -> Just (tc, ty', co1 `mkTransCoI` co2)
1298
1299         _ -> Nothing
1300
1301 isFFITy :: Type -> Bool
1302 -- True for any TyCon that can possibly be an arg or result of an FFI call
1303 isFFITy ty = checkRepTyCon legalFFITyCon ty
1304
1305 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
1306 -- Checks for valid argument type for a 'foreign import'
1307 isFFIArgumentTy dflags safety ty 
1308    = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
1309
1310 isFFIExternalTy :: Type -> Bool
1311 -- Types that are allowed as arguments of a 'foreign export'
1312 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
1313
1314 isFFIImportResultTy :: DynFlags -> Type -> Bool
1315 isFFIImportResultTy dflags ty 
1316   = checkRepTyCon (legalFIResultTyCon dflags) ty
1317
1318 isFFIExportResultTy :: Type -> Bool
1319 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
1320
1321 isFFIDynArgumentTy :: Type -> Bool
1322 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
1323 -- or a newtype of either.
1324 isFFIDynArgumentTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1325
1326 isFFIDynResultTy :: Type -> Bool
1327 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
1328 -- or a newtype of either.
1329 isFFIDynResultTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1330
1331 isFFILabelTy :: Type -> Bool
1332 -- The type of a foreign label must be Ptr, FunPtr, Addr,
1333 -- or a newtype of either.
1334 isFFILabelTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1335
1336 isFFIPrimArgumentTy :: DynFlags -> Type -> Bool
1337 -- Checks for valid argument type for a 'foreign import prim'
1338 -- Currently they must all be simple unlifted types.
1339 isFFIPrimArgumentTy dflags ty
1340    = checkRepTyCon (legalFIPrimArgTyCon dflags) ty
1341
1342 isFFIPrimResultTy :: DynFlags -> Type -> Bool
1343 -- Checks for valid result type for a 'foreign import prim'
1344 -- Currently it must be an unlifted type, including unboxed tuples.
1345 isFFIPrimResultTy dflags ty
1346    = checkRepTyCon (legalFIPrimResultTyCon dflags) ty
1347
1348 isFFIDotnetTy :: DynFlags -> Type -> Bool
1349 isFFIDotnetTy dflags ty
1350   = checkRepTyCon (\ tc -> (legalFIResultTyCon dflags tc || 
1351                            isFFIDotnetObjTy ty || isStringTy ty)) ty
1352         -- NB: isStringTy used to look through newtypes, but
1353         --     it no longer does so.  May need to adjust isFFIDotNetTy
1354         --     if we do want to look through newtypes.
1355
1356 isFFIDotnetObjTy :: Type -> Bool
1357 isFFIDotnetObjTy ty
1358   = checkRepTyCon check_tc t_ty
1359   where
1360    (_, t_ty) = tcSplitForAllTys ty
1361    check_tc tc = getName tc == objectTyConName
1362
1363 isFunPtrTy :: Type -> Bool
1364 isFunPtrTy = checkRepTyConKey [funPtrTyConKey]
1365
1366 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
1367 -- Look through newtypes, but *not* foralls
1368 -- Should work even for recursive newtypes
1369 -- eg Manuel had:       newtype T = MkT (Ptr T)
1370 checkRepTyCon check_tc ty
1371   = go [] ty
1372   where
1373     go rec_nts ty
1374       | Just (tc,tys) <- splitTyConApp_maybe ty
1375       = case carefullySplitNewType_maybe rec_nts tc tys of
1376            Just (rec_nts', ty') -> go rec_nts' ty'
1377            Nothing              -> check_tc tc
1378       | otherwise
1379       = False
1380
1381 checkRepTyConKey :: [Unique] -> Type -> Bool
1382 -- Like checkRepTyCon, but just looks at the TyCon key
1383 checkRepTyConKey keys
1384   = checkRepTyCon (\tc -> tyConUnique tc `elem` keys)
1385 \end{code}
1386
1387 ----------------------------------------------
1388 These chaps do the work; they are not exported
1389 ----------------------------------------------
1390
1391 \begin{code}
1392 legalFEArgTyCon :: TyCon -> Bool
1393 legalFEArgTyCon tc
1394   -- It's illegal to make foreign exports that take unboxed
1395   -- arguments.  The RTS API currently can't invoke such things.  --SDM 7/2000
1396   = boxedMarshalableTyCon tc
1397
1398 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
1399 legalFIResultTyCon dflags tc
1400   | tc == unitTyCon         = True
1401   | otherwise               = marshalableTyCon dflags tc
1402
1403 legalFEResultTyCon :: TyCon -> Bool
1404 legalFEResultTyCon tc
1405   | tc == unitTyCon         = True
1406   | otherwise               = boxedMarshalableTyCon tc
1407
1408 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
1409 -- Checks validity of types going from Haskell -> external world
1410 legalOutgoingTyCon dflags _ tc
1411   = marshalableTyCon dflags tc
1412
1413 legalFFITyCon :: TyCon -> Bool
1414 -- True for any TyCon that can possibly be an arg or result of an FFI call
1415 legalFFITyCon tc
1416   = isUnLiftedTyCon tc || boxedMarshalableTyCon tc || tc == unitTyCon
1417
1418 marshalableTyCon :: DynFlags -> TyCon -> Bool
1419 marshalableTyCon dflags tc
1420   =  (xopt Opt_UnliftedFFITypes dflags 
1421       && isUnLiftedTyCon tc
1422       && not (isUnboxedTupleTyCon tc)
1423       && case tyConPrimRep tc of        -- Note [Marshalling VoidRep]
1424            VoidRep -> False
1425            _       -> True)
1426   || boxedMarshalableTyCon tc
1427
1428 boxedMarshalableTyCon :: TyCon -> Bool
1429 boxedMarshalableTyCon tc
1430    = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
1431                          , int32TyConKey, int64TyConKey
1432                          , wordTyConKey, word8TyConKey, word16TyConKey
1433                          , word32TyConKey, word64TyConKey
1434                          , floatTyConKey, doubleTyConKey
1435                          , ptrTyConKey, funPtrTyConKey
1436                          , charTyConKey
1437                          , stablePtrTyConKey
1438                          , boolTyConKey
1439                          ]
1440
1441 legalFIPrimArgTyCon :: DynFlags -> TyCon -> Bool
1442 -- Check args of 'foreign import prim', only allow simple unlifted types.
1443 -- Strictly speaking it is unnecessary to ban unboxed tuples here since
1444 -- currently they're of the wrong kind to use in function args anyway.
1445 legalFIPrimArgTyCon dflags tc
1446   = xopt Opt_UnliftedFFITypes dflags
1447     && isUnLiftedTyCon tc
1448     && not (isUnboxedTupleTyCon tc)
1449
1450 legalFIPrimResultTyCon :: DynFlags -> TyCon -> Bool
1451 -- Check result type of 'foreign import prim'. Allow simple unlifted
1452 -- types and also unboxed tuple result types '... -> (# , , #)'
1453 legalFIPrimResultTyCon dflags tc
1454   = xopt Opt_UnliftedFFITypes dflags
1455     && isUnLiftedTyCon tc
1456     && (isUnboxedTupleTyCon tc
1457         || case tyConPrimRep tc of      -- Note [Marshalling VoidRep]
1458            VoidRep -> False
1459            _       -> True)
1460 \end{code}
1461
1462 Note [Marshalling VoidRep]
1463 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1464 We don't treat State# (whose PrimRep is VoidRep) as marshalable.
1465 In turn that means you can't write
1466         foreign import foo :: Int -> State# RealWorld
1467
1468 Reason: the back end falls over with panic "primRepHint:VoidRep";
1469         and there is no compelling reason to permit it