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