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