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