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