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