Make TcType warning-free
[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, 
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, tcSplitDFunTy, tcSplitDFunHead, predTyUnique, 
75   mkClassPred, isInheritablePred, isIPPred, 
76   dataConsStupidTheta, isRefineableTy, isRefineablePred,
77
78   ---------------------------------
79   -- Foreign import and export
80   isFFIArgumentTy,     -- :: DynFlags -> Safety -> Type -> Bool
81   isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
82   isFFIExportResultTy, -- :: Type -> Bool
83   isFFIExternalTy,     -- :: Type -> Bool
84   isFFIDynArgumentTy,  -- :: Type -> Bool
85   isFFIDynResultTy,    -- :: Type -> Bool
86   isFFILabelTy,        -- :: Type -> Bool
87   isFFIDotnetTy,       -- :: DynFlags -> Type -> Bool
88   isFFIDotnetObjTy,    -- :: Type -> Bool
89   isFFITy,             -- :: Type -> Bool
90   tcSplitIOType_maybe, -- :: Type -> Maybe Type  
91   toDNType,            -- :: Type -> DNType
92
93   --------------------------------
94   -- Rexported from Type
95   Kind,         -- Stuff to do with kinds is insensitive to pre/post Tc
96   unliftedTypeKind, liftedTypeKind, argTypeKind,
97   openTypeKind, mkArrowKind, mkArrowKinds, 
98   isLiftedTypeKind, isUnliftedTypeKind, isSubOpenTypeKind, 
99   isSubArgTypeKind, isSubKind, defaultKind,
100   kindVarRef, mkKindVar,  
101
102   Type, PredType(..), ThetaType, 
103   mkForAllTy, mkForAllTys, 
104   mkFunTy, mkFunTys, zipFunTys, 
105   mkTyConApp, mkAppTy, mkAppTys, applyTy, applyTys,
106   mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys, 
107
108   -- Type substitutions
109   TvSubst(..),  -- Representation visible to a few friends
110   TvSubstEnv, emptyTvSubst, substEqSpec,
111   mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
112   getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope, lookupTyVar,
113   extendTvSubst, extendTvSubstList, isInScope, mkTvSubst, zipTyEnv,
114   substTy, substTys, substTyWith, substTheta, substTyVar, substTyVars, substTyVarBndr,
115
116   isUnLiftedType,       -- Source types are always lifted
117   isUnboxedTupleType,   -- Ditto
118   isPrimitiveType, 
119
120   tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
121   tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars, tidySkolemTyVar,
122   typeKind, tidyKind,
123
124   tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
125   tcTyVarsOfType, tcTyVarsOfTypes, exactTyVarsOfType, exactTyVarsOfTypes,
126
127   pprKind, pprParendKind,
128   pprType, pprParendType, pprTypeApp, pprTyThingCategory,
129   pprPred, pprTheta, pprThetaArrow, pprClassPred
130
131   ) where
132
133 #include "HsVersions.h"
134
135 -- friends:
136 import TypeRep
137 import DataCon
138 import Class
139 import Var
140 import ForeignCall
141 import Unify
142 import VarSet
143 import Type
144 import Coercion
145 import TyCon
146
147 -- others:
148 import DynFlags
149 import CoreSyn
150 import Name
151 import NameSet
152 import VarEnv
153 import OccName
154 import PrelNames
155 import TysWiredIn
156 import BasicTypes
157 import Util
158 import Maybes
159 import ListSetOps
160 import Outputable
161 import FastString
162
163 import Data.List
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
356 -- Notes re TySynCtxt
357 -- We allow type synonyms that aren't types; e.g.  type List = []
358 --
359 -- If the RHS mentions tyvars that aren't in scope, we'll 
360 -- quantify over them:
361 --      e.g.    type T = a->a
362 -- will become  type T = forall a. a->a
363 --
364 -- With gla-exts that's right, but for H98 we should complain. 
365
366 ---------------------------------
367 -- Kind variables:
368
369 mkKindName :: Unique -> Name
370 mkKindName unique = mkSystemName unique kind_var_occ
371
372 kindVarRef :: KindVar -> IORef MetaDetails
373 kindVarRef tc = 
374   ASSERT ( isTcTyVar tc )
375   case tcTyVarDetails tc of
376     MetaTv TauTv ref -> ref
377     _                -> pprPanic "kindVarRef" (ppr tc)
378
379 mkKindVar :: Unique -> IORef MetaDetails -> KindVar
380 mkKindVar u r 
381   = mkTcTyVar (mkKindName u)
382               tySuperKind  -- not sure this is right,
383                             -- do we need kind vars for
384                             -- coercions?
385               (MetaTv TauTv r)
386
387 kind_var_occ :: OccName -- Just one for all KindVars
388                         -- They may be jiggled by tidying
389 kind_var_occ = mkOccName tvName "k"
390 \end{code}
391
392 %************************************************************************
393 %*                                                                      *
394                 Pretty-printing
395 %*                                                                      *
396 %************************************************************************
397
398 \begin{code}
399 pprTcTyVarDetails :: TcTyVarDetails -> SDoc
400 -- For debugging
401 pprTcTyVarDetails (SkolemTv _)         = ptext (sLit "sk")
402 pprTcTyVarDetails (MetaTv BoxTv _)     = ptext (sLit "box")
403 pprTcTyVarDetails (MetaTv TauTv _)     = ptext (sLit "tau")
404 pprTcTyVarDetails (MetaTv (SigTv _) _) = ptext (sLit "sig")
405
406 pprUserTypeCtxt :: UserTypeCtxt -> SDoc
407 pprUserTypeCtxt (FunSigCtxt n)  = ptext (sLit "the type signature for") <+> quotes (ppr n)
408 pprUserTypeCtxt ExprSigCtxt     = ptext (sLit "an expression type signature")
409 pprUserTypeCtxt (ConArgCtxt c)  = ptext (sLit "the type of the constructor") <+> quotes (ppr c)
410 pprUserTypeCtxt (TySynCtxt c)   = ptext (sLit "the RHS of the type synonym") <+> quotes (ppr c)
411 pprUserTypeCtxt GenPatCtxt      = ptext (sLit "the type pattern of a generic definition")
412 pprUserTypeCtxt LamPatSigCtxt   = ptext (sLit "a pattern type signature")
413 pprUserTypeCtxt BindPatSigCtxt  = ptext (sLit "a pattern type signature")
414 pprUserTypeCtxt ResSigCtxt      = ptext (sLit "a result type signature")
415 pprUserTypeCtxt (ForSigCtxt n)  = ptext (sLit "the foreign declaration for") <+> quotes (ppr n)
416 pprUserTypeCtxt DefaultDeclCtxt = ptext (sLit "a type in a `default' declaration")
417 pprUserTypeCtxt SpecInstCtxt    = ptext (sLit "a SPECIALISE instance pragma")
418
419
420 --------------------------------
421 tidySkolemTyVar :: TidyEnv -> TcTyVar -> (TidyEnv, TcTyVar)
422 -- Tidy the type inside a GenSkol, preparatory to printing it
423 tidySkolemTyVar env tv
424   = ASSERT( isSkolemTyVar tv || isSigTyVar tv )
425     (env1, mkTcTyVar (tyVarName tv) (tyVarKind tv) info1)
426   where
427     (env1, info1) = case tcTyVarDetails tv of
428                         SkolemTv info -> (env1, SkolemTv info')
429                                 where
430                                   (env1, info') = tidy_skol_info env info
431                         MetaTv (SigTv info) box -> (env1, MetaTv (SigTv info') box)
432                                 where
433                                   (env1, info') = tidy_skol_info env info
434                         info -> (env, info)
435
436     tidy_skol_info env (GenSkol tvs ty) = (env2, GenSkol tvs1 ty1)
437                             where
438                               (env1, tvs1) = tidyOpenTyVars env tvs
439                               (env2, ty1)  = tidyOpenType env1 ty
440     tidy_skol_info env info = (env, info)
441                      
442 pprSkolTvBinding :: TcTyVar -> SDoc
443 -- Print info about the binding of a skolem tyvar, 
444 -- or nothing if we don't have anything useful to say
445 pprSkolTvBinding tv
446   = ASSERT ( isTcTyVar tv )
447     quotes (ppr tv) <+> ppr_details (tcTyVarDetails tv)
448   where
449     ppr_details (MetaTv TauTv _)        = ptext (sLit "is a meta type variable")
450     ppr_details (MetaTv BoxTv _)        = ptext (sLit "is a boxy type variable")
451     ppr_details (MetaTv (SigTv info) _) = ppr_skol info
452     ppr_details (SkolemTv info)         = ppr_skol info
453
454     ppr_skol UnkSkol        = ptext (sLit "is an unknown type variable")        -- Unhelpful
455     ppr_skol RuntimeUnkSkol = ptext (sLit "is an unknown runtime type")
456     ppr_skol info           = sep [ptext (sLit "is a rigid type variable bound by"),
457                                    sep [pprSkolInfo info, 
458                                          nest 2 (ptext (sLit "at") <+> ppr (getSrcLoc tv))]]
459  
460 pprSkolInfo :: SkolemInfo -> SDoc
461 pprSkolInfo (SigSkol ctxt)   = pprUserTypeCtxt ctxt
462 pprSkolInfo (ClsSkol cls)    = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
463 pprSkolInfo InstSkol         = ptext (sLit "the instance declaration")
464 pprSkolInfo FamInstSkol      = ptext (sLit "the family instance declaration")
465 pprSkolInfo (RuleSkol name)  = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
466 pprSkolInfo ArrowSkol        = ptext (sLit "the arrow form")
467 pprSkolInfo (PatSkol dc)     = sep [ptext (sLit "the constructor") <+> quotes (ppr dc)]
468 pprSkolInfo (GenSkol tvs ty) = sep [ptext (sLit "the polymorphic type"), 
469                                     nest 2 (quotes (ppr (mkForAllTys tvs ty)))]
470
471 -- UnkSkol
472 -- For type variables the others are dealt with by pprSkolTvBinding.  
473 -- For Insts, these cases should not happen
474 pprSkolInfo UnkSkol = panic "UnkSkol"
475 pprSkolInfo RuntimeUnkSkol = panic "RuntimeUnkSkol"
476
477 instance Outputable MetaDetails where
478   ppr Flexi         = ptext (sLit "Flexi")
479   ppr (Indirect ty) = ptext (sLit "Indirect") <+> ppr ty
480 \end{code}
481
482
483 %************************************************************************
484 %*                                                                      *
485                 Predicates
486 %*                                                                      *
487 %************************************************************************
488
489 \begin{code}
490 isImmutableTyVar :: TyVar -> Bool
491
492 isImmutableTyVar tv
493   | isTcTyVar tv = isSkolemTyVar tv
494   | otherwise    = True
495
496 isTyConableTyVar, isSkolemTyVar, isExistentialTyVar, 
497   isBoxyTyVar, isMetaTyVar :: TcTyVar -> Bool 
498
499 isTyConableTyVar tv     
500         -- True of a meta-type variable that can be filled in 
501         -- with a type constructor application; in particular,
502         -- not a SigTv
503   = ASSERT( isTcTyVar tv) 
504     case tcTyVarDetails tv of
505         MetaTv BoxTv      _ -> True
506         MetaTv TauTv      _ -> True
507         MetaTv (SigTv {}) _ -> False
508         SkolemTv {}         -> False
509         
510 isSkolemTyVar tv 
511   = ASSERT( isTcTyVar tv )
512     case tcTyVarDetails tv of
513         SkolemTv _         -> True
514         MetaTv _ _         -> False
515
516 isExistentialTyVar tv   -- Existential type variable, bound by a pattern
517   = ASSERT( isTcTyVar tv )
518     case tcTyVarDetails tv of
519         SkolemTv (PatSkol {}) -> True
520         _                     -> False
521
522 isMetaTyVar tv 
523   = ASSERT2( isTcTyVar tv, ppr tv )
524     case tcTyVarDetails tv of
525         MetaTv _ _ -> True
526         _          -> False
527
528 isBoxyTyVar tv 
529   = ASSERT( isTcTyVar tv )
530     case tcTyVarDetails tv of
531         MetaTv BoxTv _ -> True
532         _              -> False
533
534 isSigTyVar :: Var -> Bool
535 isSigTyVar tv 
536   = ASSERT( isTcTyVar tv )
537     case tcTyVarDetails tv of
538         MetaTv (SigTv _) _ -> True
539         _                  -> False
540
541 metaTvRef :: TyVar -> IORef MetaDetails
542 metaTvRef tv 
543   = ASSERT2( isTcTyVar tv, ppr tv )
544     case tcTyVarDetails tv of
545         MetaTv _ ref -> ref
546         _          -> pprPanic "metaTvRef" (ppr tv)
547
548 isFlexi, isIndirect :: MetaDetails -> Bool
549 isFlexi Flexi = True
550 isFlexi _     = False
551
552 isIndirect (Indirect _) = True
553 isIndirect _            = False
554
555 isRuntimeUnk :: TyVar -> Bool
556 isRuntimeUnk x | isTcTyVar x
557                , SkolemTv RuntimeUnkSkol <- tcTyVarDetails x = True
558                | otherwise = False
559
560 isUnk :: TyVar -> Bool
561 isUnk x | isTcTyVar x
562         , SkolemTv UnkSkol <- tcTyVarDetails x = True
563         | otherwise = False
564 \end{code}
565
566
567 %************************************************************************
568 %*                                                                      *
569 \subsection{Tau, sigma and rho}
570 %*                                                                      *
571 %************************************************************************
572
573 \begin{code}
574 mkSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
575 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
576
577 mkPhiTy :: [PredType] -> Type -> Type
578 mkPhiTy theta ty = foldr (\p r -> mkFunTy (mkPredTy p) r) ty theta
579 \end{code}
580
581 @isTauTy@ tests for nested for-alls.  It should not be called on a boxy type.
582
583 \begin{code}
584 isTauTy :: Type -> Bool
585 isTauTy ty | Just ty' <- tcView ty = isTauTy ty'
586 isTauTy (TyVarTy tv)     = ASSERT( not (isTcTyVar tv && isBoxyTyVar tv) )
587                            True
588 isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc
589 isTauTy (AppTy a b)       = isTauTy a && isTauTy b
590 isTauTy (FunTy a b)       = isTauTy a && isTauTy b
591 isTauTy (PredTy _)        = True                -- Don't look through source types
592 isTauTy _                 = False
593
594
595 isTauTyCon :: TyCon -> Bool
596 -- Returns False for type synonyms whose expansion is a polytype
597 isTauTyCon tc 
598   | isClosedSynTyCon tc = isTauTy (snd (synTyConDefn tc))
599   | otherwise           = True
600
601 ---------------
602 isBoxyTy :: TcType -> Bool
603 isBoxyTy ty = any isBoxyTyVar (varSetElems (tcTyVarsOfType ty))
604
605 isRigidTy :: TcType -> Bool
606 -- A type is rigid if it has no meta type variables in it
607 isRigidTy ty = all isImmutableTyVar (varSetElems (tcTyVarsOfType ty))
608
609 isRefineableTy :: TcType -> (Bool,Bool)
610 -- A type should have type refinements applied to it if it has
611 -- free type variables, and they are all rigid
612 isRefineableTy ty = (null tc_tvs,  all isImmutableTyVar tc_tvs)
613                     where
614                       tc_tvs = varSetElems (tcTyVarsOfType ty)
615
616 isRefineablePred :: TcPredType -> Bool
617 isRefineablePred pred = not (null tc_tvs) && all isImmutableTyVar tc_tvs
618                       where
619                         tc_tvs = varSetElems (tcTyVarsOfPred pred)
620
621 ---------------
622 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to 
623                                 -- construct a dictionary function name
624 getDFunTyKey ty | Just ty' <- tcView ty = getDFunTyKey ty'
625 getDFunTyKey (TyVarTy tv)    = getOccName tv
626 getDFunTyKey (TyConApp tc _) = getOccName tc
627 getDFunTyKey (AppTy fun _)   = getDFunTyKey fun
628 getDFunTyKey (FunTy _ _)     = getOccName funTyCon
629 getDFunTyKey (ForAllTy _ t)  = getDFunTyKey t
630 getDFunTyKey ty              = pprPanic "getDFunTyKey" (pprType ty)
631 -- PredTy shouldn't happen
632 \end{code}
633
634
635 %************************************************************************
636 %*                                                                      *
637 \subsection{Expanding and splitting}
638 %*                                                                      *
639 %************************************************************************
640
641 These tcSplit functions are like their non-Tc analogues, but
642         a) they do not look through newtypes
643         b) they do not look through PredTys
644         c) [future] they ignore usage-type annotations
645
646 However, they are non-monadic and do not follow through mutable type
647 variables.  It's up to you to make sure this doesn't matter.
648
649 \begin{code}
650 tcSplitForAllTys :: Type -> ([TyVar], Type)
651 tcSplitForAllTys ty = split ty ty []
652    where
653      split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
654      split _ (ForAllTy tv ty) tvs 
655        | not (isCoVar tv) = split ty ty (tv:tvs)
656      split orig_ty _ tvs = (reverse tvs, orig_ty)
657
658 tcIsForAllTy :: Type -> Bool
659 tcIsForAllTy ty | Just ty' <- tcView ty = tcIsForAllTy ty'
660 tcIsForAllTy (ForAllTy tv _) = not (isCoVar tv)
661 tcIsForAllTy _               = False
662
663 tcSplitPhiTy :: Type -> (ThetaType, Type)
664 tcSplitPhiTy ty = split ty ty []
665  where
666   split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
667
668   split _       (ForAllTy tv ty) ts
669         | isCoVar tv = split ty ty (coVarPred tv : ts)
670   split _        (FunTy arg res) ts 
671         | Just p <- tcSplitPredTy_maybe arg = split res res (p:ts)
672   split orig_ty _               ts = (reverse ts, orig_ty)
673
674 tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
675 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
676                         (tvs, rho) -> case tcSplitPhiTy rho of
677                                         (theta, tau) -> (tvs, theta, tau)
678
679 -----------------------
680 tcMultiSplitSigmaTy
681         :: TcSigmaType
682         -> ( [([TyVar], ThetaType)],    -- forall as.C => forall bs.D
683              TcSigmaType)               -- The rest of the type
684
685 -- We need a loop here because we are now prepared to entertain
686 -- types like
687 --      f:: forall a. Eq a => forall b. Baz b => tau
688 -- We want to instantiate this to
689 --      f2::tau         {f2 = f1 b (Baz b), f1 = f a (Eq a)}
690
691 tcMultiSplitSigmaTy sigma
692   = case (tcSplitSigmaTy sigma) of
693         ([], [], _) -> ([], sigma)
694         (tvs, theta, ty) -> case tcMultiSplitSigmaTy ty of
695                                 (pairs, rest) -> ((tvs,theta):pairs, rest)
696
697 -----------------------
698 tcTyConAppTyCon :: Type -> TyCon
699 tcTyConAppTyCon ty = case tcSplitTyConApp_maybe ty of
700                         Just (tc, _) -> tc
701                         Nothing      -> pprPanic "tcTyConAppTyCon" (pprType ty)
702
703 tcTyConAppArgs :: Type -> [Type]
704 tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of
705                         Just (_, args) -> args
706                         Nothing        -> pprPanic "tcTyConAppArgs" (pprType ty)
707
708 tcSplitTyConApp :: Type -> (TyCon, [Type])
709 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
710                         Just stuff -> stuff
711                         Nothing    -> pprPanic "tcSplitTyConApp" (pprType ty)
712
713 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
714 tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty'
715 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
716 tcSplitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
717         -- Newtypes are opaque, so they may be split
718         -- However, predicates are not treated
719         -- as tycon applications by the type checker
720 tcSplitTyConApp_maybe _                 = Nothing
721
722 -----------------------
723 tcSplitFunTys :: Type -> ([Type], Type)
724 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
725                         Nothing        -> ([], ty)
726                         Just (arg,res) -> (arg:args, res')
727                                        where
728                                           (args,res') = tcSplitFunTys res
729
730 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
731 tcSplitFunTy_maybe ty | Just ty' <- tcView ty           = tcSplitFunTy_maybe ty'
732 tcSplitFunTy_maybe (FunTy arg res) | not (isPredTy arg) = Just (arg, res)
733 tcSplitFunTy_maybe _                                    = Nothing
734         -- Note the (not (isPredTy arg)) guard
735         -- Consider     (?x::Int) => Bool
736         -- We don't want to treat this as a function type!
737         -- A concrete example is test tc230:
738         --      f :: () -> (?p :: ()) => () -> ()
739         --
740         --      g = f () ()
741
742 tcSplitFunTysN
743         :: TcRhoType 
744         -> Arity                -- N: Number of desired args
745         -> ([TcSigmaType],      -- Arg types (N or fewer)
746             TcSigmaType)        -- The rest of the type
747
748 tcSplitFunTysN ty n_args
749   | n_args == 0
750   = ([], ty)
751   | Just (arg,res) <- tcSplitFunTy_maybe ty
752   = case tcSplitFunTysN res (n_args - 1) of
753         (args, res) -> (arg:args, res)
754   | otherwise
755   = ([], ty)
756
757 tcSplitFunTy :: Type -> (Type, Type)
758 tcSplitFunTy  ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
759
760 tcFunArgTy :: Type -> Type
761 tcFunArgTy    ty = fst (tcSplitFunTy ty)
762
763 tcFunResultTy :: Type -> Type
764 tcFunResultTy ty = snd (tcSplitFunTy ty)
765
766 -----------------------
767 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
768 tcSplitAppTy_maybe ty | Just ty' <- tcView ty = tcSplitAppTy_maybe ty'
769 tcSplitAppTy_maybe ty = repSplitAppTy_maybe ty
770
771 tcSplitAppTy :: Type -> (Type, Type)
772 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
773                     Just stuff -> stuff
774                     Nothing    -> pprPanic "tcSplitAppTy" (pprType ty)
775
776 tcSplitAppTys :: Type -> (Type, [Type])
777 tcSplitAppTys ty
778   = go ty []
779   where
780     go ty args = case tcSplitAppTy_maybe ty of
781                    Just (ty', arg) -> go ty' (arg:args)
782                    Nothing         -> (ty,args)
783
784 -----------------------
785 tcGetTyVar_maybe :: Type -> Maybe TyVar
786 tcGetTyVar_maybe ty | Just ty' <- tcView ty = tcGetTyVar_maybe ty'
787 tcGetTyVar_maybe (TyVarTy tv)   = Just tv
788 tcGetTyVar_maybe _              = Nothing
789
790 tcGetTyVar :: String -> Type -> TyVar
791 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
792
793 tcIsTyVarTy :: Type -> Bool
794 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
795
796 -----------------------
797 tcSplitDFunTy :: Type -> ([TyVar], [PredType], Class, [Type])
798 -- Split the type of a dictionary function
799 tcSplitDFunTy ty 
800   = case tcSplitSigmaTy ty   of { (tvs, theta, tau) ->
801     case tcSplitDFunHead tau of { (clas, tys) -> 
802     (tvs, theta, clas, tys) }}
803
804 tcSplitDFunHead :: Type -> (Class, [Type])
805 tcSplitDFunHead tau  
806   = case tcSplitPredTy_maybe tau of 
807         Just (ClassP clas tys) -> (clas, tys)
808         _ -> panic "tcSplitDFunHead"
809
810 tcInstHeadTyNotSynonym :: Type -> Bool
811 -- Used in Haskell-98 mode, for the argument types of an instance head
812 -- These must not be type synonyms, but everywhere else type synonyms
813 -- are transparent, so we need a special function here
814 tcInstHeadTyNotSynonym ty
815   = case ty of
816         TyConApp tc _ -> not (isSynTyCon tc)
817         _ -> True
818
819 tcInstHeadTyAppAllTyVars :: Type -> Bool
820 -- Used in Haskell-98 mode, for the argument types of an instance head
821 -- These must be a constructor applied to type variable arguments
822 tcInstHeadTyAppAllTyVars ty
823   = case ty of
824         TyConApp _ tys  -> ok tys
825         FunTy arg res   -> ok [arg, res]
826         _               -> False
827   where
828         -- Check that all the types are type variables,
829         -- and that each is distinct
830     ok tys = equalLength tvs tys && hasNoDups tvs
831            where
832              tvs = mapCatMaybes get_tv tys
833
834     get_tv (TyVarTy tv)  = Just tv      -- through synonyms
835     get_tv _             = Nothing
836 \end{code}
837
838
839
840 %************************************************************************
841 %*                                                                      *
842 \subsection{Predicate types}
843 %*                                                                      *
844 %************************************************************************
845
846 \begin{code}
847 tcSplitPredTy_maybe :: Type -> Maybe PredType
848    -- Returns Just for predicates only
849 tcSplitPredTy_maybe ty | Just ty' <- tcView ty = tcSplitPredTy_maybe ty'
850 tcSplitPredTy_maybe (PredTy p)    = Just p
851 tcSplitPredTy_maybe _             = Nothing
852
853 predTyUnique :: PredType -> Unique
854 predTyUnique (IParam n _)    = getUnique (ipNameName n)
855 predTyUnique (ClassP clas _) = getUnique clas
856 predTyUnique (EqPred a b)    = pprPanic "predTyUnique" (ppr (EqPred a b))
857 \end{code}
858
859
860 --------------------- Dictionary types ---------------------------------
861
862 \begin{code}
863 mkClassPred :: Class -> [Type] -> PredType
864 mkClassPred clas tys = ClassP clas tys
865
866 isClassPred :: PredType -> Bool
867 isClassPred (ClassP _ _) = True
868 isClassPred _            = False
869
870 isTyVarClassPred :: PredType -> Bool
871 isTyVarClassPred (ClassP _ tys) = all tcIsTyVarTy tys
872 isTyVarClassPred _              = False
873
874 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
875 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
876 getClassPredTys_maybe _                 = Nothing
877
878 getClassPredTys :: PredType -> (Class, [Type])
879 getClassPredTys (ClassP clas tys) = (clas, tys)
880 getClassPredTys _ = panic "getClassPredTys"
881
882 mkDictTy :: Class -> [Type] -> Type
883 mkDictTy clas tys = mkPredTy (ClassP clas tys)
884
885 isDictTy :: Type -> Bool
886 isDictTy ty | Just ty' <- tcView ty = isDictTy ty'
887 isDictTy (PredTy p) = isClassPred p
888 isDictTy _          = False
889 \end{code}
890
891 --------------------- Implicit parameters ---------------------------------
892
893 \begin{code}
894 isIPPred :: PredType -> Bool
895 isIPPred (IParam _ _) = True
896 isIPPred _            = False
897
898 isInheritablePred :: PredType -> Bool
899 -- Can be inherited by a context.  For example, consider
900 --      f x = let g y = (?v, y+x)
901 --            in (g 3 with ?v = 8, 
902 --                g 4 with ?v = 9)
903 -- The point is that g's type must be quantifed over ?v:
904 --      g :: (?v :: a) => a -> a
905 -- but it doesn't need to be quantified over the Num a dictionary
906 -- which can be free in g's rhs, and shared by both calls to g
907 isInheritablePred (ClassP _ _) = True
908 isInheritablePred (EqPred _ _) = True
909 isInheritablePred _            = False
910 \end{code}
911
912 --------------------- Equality predicates ---------------------------------
913 \begin{code}
914 substEqSpec :: TvSubst -> [(TyVar,Type)] -> [(TcType,TcType)]
915 substEqSpec subst eq_spec = [ (substTyVar subst tv, substTy subst ty)
916                             | (tv,ty) <- eq_spec]
917 \end{code}
918
919 --------------------- The stupid theta (sigh) ---------------------------------
920
921 \begin{code}
922 dataConsStupidTheta :: [DataCon] -> ThetaType
923 -- Union the stupid thetas from all the specified constructors (non-empty)
924 -- All the constructors should have the same result type, modulo alpha conversion
925 -- The resulting ThetaType uses type variables from the *first* constructor in the list
926 --
927 -- It's here because it's used in MkId.mkRecordSelId, and in TcExpr
928 dataConsStupidTheta (con1:cons)
929   = nubBy tcEqPred all_preds
930   where
931     all_preds     = dataConStupidTheta con1 ++ other_stupids
932     res_ty1       = dataConOrigResTy con1
933     other_stupids = [ substPred subst pred
934                     | con <- cons
935                     , let (tvs, _, _, res_ty) = dataConSig con
936                           Just subst = tcMatchTy (mkVarSet tvs) res_ty res_ty1
937                     , pred <- dataConStupidTheta con ]
938 dataConsStupidTheta [] = panic "dataConsStupidTheta"
939 \end{code}
940
941
942 %************************************************************************
943 %*                                                                      *
944 \subsection{Predicates}
945 %*                                                                      *
946 %************************************************************************
947
948 isSigmaTy returns true of any qualified type.  It doesn't *necessarily* have 
949 any foralls.  E.g.
950         f :: (?x::Int) => Int -> Int
951
952 \begin{code}
953 isSigmaTy :: Type -> Bool
954 isSigmaTy ty | Just ty' <- tcView ty = isSigmaTy ty'
955 isSigmaTy (ForAllTy _ _) = True
956 isSigmaTy (FunTy a _)    = isPredTy a
957 isSigmaTy _              = False
958
959 isOverloadedTy :: Type -> Bool
960 isOverloadedTy ty | Just ty' <- tcView ty = isOverloadedTy ty'
961 isOverloadedTy (ForAllTy _ ty) = isOverloadedTy ty
962 isOverloadedTy (FunTy a _)     = isPredTy a
963 isOverloadedTy _               = False
964
965 isPredTy :: Type -> Bool        -- Belongs in TcType because it does 
966                                 -- not look through newtypes, or predtypes (of course)
967 isPredTy ty | Just ty' <- tcView ty = isPredTy ty'
968 isPredTy (PredTy _) = True
969 isPredTy _          = False
970 \end{code}
971
972 \begin{code}
973 isFloatTy, isDoubleTy, isIntegerTy, isIntTy, isWordTy, isBoolTy,
974     isUnitTy, isCharTy :: Type -> Bool
975 isFloatTy      = is_tc floatTyConKey
976 isDoubleTy     = is_tc doubleTyConKey
977 isIntegerTy    = is_tc integerTyConKey
978 isIntTy        = is_tc intTyConKey
979 isWordTy       = is_tc wordTyConKey
980 isBoolTy       = is_tc boolTyConKey
981 isUnitTy       = is_tc unitTyConKey
982 isCharTy       = is_tc charTyConKey
983
984 isStringTy :: Type -> Bool
985 isStringTy ty
986   = case tcSplitTyConApp_maybe ty of
987       Just (tc, [arg_ty]) -> tc == listTyCon && isCharTy arg_ty
988       _                   -> False
989
990 is_tc :: Unique -> Type -> Bool
991 -- Newtypes are opaque to this
992 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
993                         Just (tc, _) -> uniq == getUnique tc
994                         Nothing      -> False
995 \end{code}
996
997 \begin{code}
998 -- NB: Currently used in places where we have already expanded type synonyms;
999 --     hence no 'coreView'.  This could, however, be changed without breaking
1000 --     any code.
1001 isOpenSynTyConApp :: TcTauType -> Bool
1002 isOpenSynTyConApp (TyConApp tc _) = isOpenSynTyCon tc
1003 isOpenSynTyConApp _other          = False
1004 \end{code}
1005
1006
1007 %************************************************************************
1008 %*                                                                      *
1009 \subsection{Misc}
1010 %*                                                                      *
1011 %************************************************************************
1012
1013 \begin{code}
1014 deNoteType :: Type -> Type
1015 -- Remove all *outermost* type synonyms and other notes
1016 deNoteType ty | Just ty' <- tcView ty = deNoteType ty'
1017 deNoteType ty = ty
1018 \end{code}
1019
1020 \begin{code}
1021 tcTyVarsOfType :: Type -> TcTyVarSet
1022 -- Just the *TcTyVars* free in the type
1023 -- (Types.tyVarsOfTypes finds all free TyVars)
1024 tcTyVarsOfType (TyVarTy tv)         = if isTcTyVar tv then unitVarSet tv
1025                                                       else emptyVarSet
1026 tcTyVarsOfType (TyConApp _ tys)     = tcTyVarsOfTypes tys
1027 tcTyVarsOfType (PredTy sty)         = tcTyVarsOfPred sty
1028 tcTyVarsOfType (FunTy arg res)      = tcTyVarsOfType arg `unionVarSet` tcTyVarsOfType res
1029 tcTyVarsOfType (AppTy fun arg)      = tcTyVarsOfType fun `unionVarSet` tcTyVarsOfType arg
1030 tcTyVarsOfType (ForAllTy tyvar ty)  = (tcTyVarsOfType ty `delVarSet` tyvar)
1031                                       `unionVarSet` tcTyVarsOfTyVar tyvar
1032         -- We do sometimes quantify over skolem TcTyVars
1033
1034 tcTyVarsOfTyVar :: TcTyVar -> TyVarSet
1035 tcTyVarsOfTyVar tv | isCoVar tv = tcTyVarsOfType (tyVarKind tv)
1036                    | otherwise  = emptyVarSet
1037
1038 tcTyVarsOfTypes :: [Type] -> TyVarSet
1039 tcTyVarsOfTypes tys = foldr (unionVarSet.tcTyVarsOfType) emptyVarSet tys
1040
1041 tcTyVarsOfPred :: PredType -> TyVarSet
1042 tcTyVarsOfPred (IParam _ ty)    = tcTyVarsOfType ty
1043 tcTyVarsOfPred (ClassP _ tys)   = tcTyVarsOfTypes tys
1044 tcTyVarsOfPred (EqPred ty1 ty2) = tcTyVarsOfType ty1 `unionVarSet` tcTyVarsOfType ty2
1045 \end{code}
1046
1047 Note [Silly type synonym]
1048 ~~~~~~~~~~~~~~~~~~~~~~~~~
1049 Consider
1050         type T a = Int
1051 What are the free tyvars of (T x)?  Empty, of course!  
1052 Here's the example that Ralf Laemmel showed me:
1053         foo :: (forall a. C u a -> C u a) -> u
1054         mappend :: Monoid u => u -> u -> u
1055
1056         bar :: Monoid u => u
1057         bar = foo (\t -> t `mappend` t)
1058 We have to generalise at the arg to f, and we don't
1059 want to capture the constraint (Monad (C u a)) because
1060 it appears to mention a.  Pretty silly, but it was useful to him.
1061
1062 exactTyVarsOfType is used by the type checker to figure out exactly
1063 which type variables are mentioned in a type.  It's also used in the
1064 smart-app checking code --- see TcExpr.tcIdApp
1065
1066 On the other hand, consider a *top-level* definition
1067         f = (\x -> x) :: T a -> T a
1068 If we don't abstract over 'a' it'll get fixed to GHC.Prim.Any, and then
1069 if we have an application like (f "x") we get a confusing error message 
1070 involving Any.  So the conclusion is this: when generalising
1071   - at top level use tyVarsOfType
1072   - in nested bindings use exactTyVarsOfType
1073 See Trac #1813 for example.
1074
1075 \begin{code}
1076 exactTyVarsOfType :: TcType -> TyVarSet
1077 -- Find the free type variables (of any kind)
1078 -- but *expand* type synonyms.  See Note [Silly type synonym] above.
1079 exactTyVarsOfType ty
1080   = go ty
1081   where
1082     go ty | Just ty' <- tcView ty = go ty'      -- This is the key line
1083     go (TyVarTy tv)               = unitVarSet tv
1084     go (TyConApp _ tys)           = exactTyVarsOfTypes tys
1085     go (PredTy ty)                = go_pred ty
1086     go (FunTy arg res)            = go arg `unionVarSet` go res
1087     go (AppTy fun arg)            = go fun `unionVarSet` go arg
1088     go (ForAllTy tyvar ty)        = delVarSet (go ty) tyvar
1089                                     `unionVarSet` go_tv tyvar
1090
1091     go_pred (IParam _ ty)    = go ty
1092     go_pred (ClassP _ tys)   = exactTyVarsOfTypes tys
1093     go_pred (EqPred ty1 ty2) = go ty1 `unionVarSet` go ty2
1094
1095     go_tv tyvar | isCoVar tyvar = go (tyVarKind tyvar)
1096                 | otherwise     = emptyVarSet
1097
1098 exactTyVarsOfTypes :: [TcType] -> TyVarSet
1099 exactTyVarsOfTypes tys = foldr (unionVarSet . exactTyVarsOfType) emptyVarSet tys
1100 \end{code}
1101
1102 Find the free tycons and classes of a type.  This is used in the front
1103 end of the compiler.
1104
1105 \begin{code}
1106 tyClsNamesOfType :: Type -> NameSet
1107 tyClsNamesOfType (TyVarTy _)                = emptyNameSet
1108 tyClsNamesOfType (TyConApp tycon tys)       = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
1109 tyClsNamesOfType (PredTy (IParam _ ty))     = tyClsNamesOfType ty
1110 tyClsNamesOfType (PredTy (ClassP cl tys))   = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
1111 tyClsNamesOfType (PredTy (EqPred ty1 ty2))  = tyClsNamesOfType ty1 `unionNameSets` tyClsNamesOfType ty2
1112 tyClsNamesOfType (FunTy arg res)            = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
1113 tyClsNamesOfType (AppTy fun arg)            = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
1114 tyClsNamesOfType (ForAllTy _ ty)            = tyClsNamesOfType ty
1115
1116 tyClsNamesOfTypes :: [Type] -> NameSet
1117 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
1118
1119 tyClsNamesOfDFunHead :: Type -> NameSet
1120 -- Find the free type constructors and classes 
1121 -- of the head of the dfun instance type
1122 -- The 'dfun_head_type' is because of
1123 --      instance Foo a => Baz T where ...
1124 -- The decl is an orphan if Baz and T are both not locally defined,
1125 --      even if Foo *is* locally defined
1126 tyClsNamesOfDFunHead dfun_ty 
1127   = case tcSplitSigmaTy dfun_ty of
1128         (_, _, head_ty) -> tyClsNamesOfType head_ty
1129 \end{code}
1130
1131
1132 %************************************************************************
1133 %*                                                                      *
1134 \subsection[TysWiredIn-ext-type]{External types}
1135 %*                                                                      *
1136 %************************************************************************
1137
1138 The compiler's foreign function interface supports the passing of a
1139 restricted set of types as arguments and results (the restricting factor
1140 being the )
1141
1142 \begin{code}
1143 tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type, CoercionI)
1144 -- (isIOType t) returns Just (IO,t',co)
1145 --                              if co : t ~ IO t'
1146 --              returns Nothing otherwise
1147 tcSplitIOType_maybe ty 
1148   = case tcSplitTyConApp_maybe ty of
1149         -- This split absolutely has to be a tcSplit, because we must
1150         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
1151
1152         Just (io_tycon, [io_res_ty]) 
1153            |  io_tycon `hasKey` ioTyConKey 
1154            -> Just (io_tycon, io_res_ty, IdCo)
1155
1156         Just (tc, tys)
1157            | not (isRecursiveTyCon tc)
1158            , Just (ty, co1) <- instNewTyCon_maybe tc tys
1159                   -- Newtypes that require a coercion are ok
1160            -> case tcSplitIOType_maybe ty of
1161                 Nothing             -> Nothing
1162                 Just (tc, ty', co2) -> Just (tc, ty', co1 `mkTransCoI` co2)
1163
1164         _ -> Nothing
1165
1166 isFFITy :: Type -> Bool
1167 -- True for any TyCon that can possibly be an arg or result of an FFI call
1168 isFFITy ty = checkRepTyCon legalFFITyCon ty
1169
1170 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
1171 -- Checks for valid argument type for a 'foreign import'
1172 isFFIArgumentTy dflags safety ty 
1173    = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
1174
1175 isFFIExternalTy :: Type -> Bool
1176 -- Types that are allowed as arguments of a 'foreign export'
1177 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
1178
1179 isFFIImportResultTy :: DynFlags -> Type -> Bool
1180 isFFIImportResultTy dflags ty 
1181   = checkRepTyCon (legalFIResultTyCon dflags) ty
1182
1183 isFFIExportResultTy :: Type -> Bool
1184 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
1185
1186 isFFIDynArgumentTy :: Type -> Bool
1187 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
1188 -- or a newtype of either.
1189 isFFIDynArgumentTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1190
1191 isFFIDynResultTy :: Type -> Bool
1192 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
1193 -- or a newtype of either.
1194 isFFIDynResultTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1195
1196 isFFILabelTy :: Type -> Bool
1197 -- The type of a foreign label must be Ptr, FunPtr, Addr,
1198 -- or a newtype of either.
1199 isFFILabelTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1200
1201 isFFIDotnetTy :: DynFlags -> Type -> Bool
1202 isFFIDotnetTy dflags ty
1203   = checkRepTyCon (\ tc -> (legalFIResultTyCon dflags tc || 
1204                            isFFIDotnetObjTy ty || isStringTy ty)) ty
1205         -- NB: isStringTy used to look through newtypes, but
1206         --     it no longer does so.  May need to adjust isFFIDotNetTy
1207         --     if we do want to look through newtypes.
1208
1209 isFFIDotnetObjTy :: Type -> Bool
1210 isFFIDotnetObjTy ty
1211   = checkRepTyCon check_tc t_ty
1212   where
1213    (_, t_ty) = tcSplitForAllTys ty
1214    check_tc tc = getName tc == objectTyConName
1215
1216 toDNType :: Type -> DNType
1217 toDNType ty
1218   | isStringTy ty = DNString
1219   | isFFIDotnetObjTy ty = DNObject
1220   | Just (tc,argTys) <- tcSplitTyConApp_maybe ty 
1221   =  case lookup (getUnique tc) dn_assoc of
1222        Just x  -> x
1223        Nothing 
1224          | tc `hasKey` ioTyConKey -> toDNType (head argTys)
1225          | otherwise -> pprPanic ("toDNType: unsupported .NET type") 
1226                           (pprType ty <+> parens (hcat (map pprType argTys)) <+> ppr tc)
1227   | otherwise = panic "toDNType"        -- Is this right?
1228     where
1229       dn_assoc :: [ (Unique, DNType) ]
1230       dn_assoc = [ (unitTyConKey,   DNUnit)
1231                  , (intTyConKey,    DNInt)
1232                  , (int8TyConKey,   DNInt8)
1233                  , (int16TyConKey,  DNInt16)
1234                  , (int32TyConKey,  DNInt32)
1235                  , (int64TyConKey,  DNInt64)
1236                  , (wordTyConKey,   DNInt)
1237                  , (word8TyConKey,  DNWord8)
1238                  , (word16TyConKey, DNWord16)
1239                  , (word32TyConKey, DNWord32)
1240                  , (word64TyConKey, DNWord64)
1241                  , (floatTyConKey,  DNFloat)
1242                  , (doubleTyConKey, DNDouble)
1243                  , (ptrTyConKey,    DNPtr)
1244                  , (funPtrTyConKey, DNPtr)
1245                  , (charTyConKey,   DNChar)
1246                  , (boolTyConKey,   DNBool)
1247                  ]
1248
1249 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
1250         -- Look through newtypes
1251         -- Non-recursive ones are transparent to splitTyConApp,
1252         -- but recursive ones aren't.  Manuel had:
1253         --      newtype T = MkT (Ptr T)
1254         -- and wanted it to work...
1255 checkRepTyCon check_tc ty 
1256   | Just (tc,_) <- splitTyConApp_maybe (repType ty) = check_tc tc
1257   | otherwise                                       = False
1258
1259 checkRepTyConKey :: [Unique] -> Type -> Bool
1260 -- Like checkRepTyCon, but just looks at the TyCon key
1261 checkRepTyConKey keys
1262   = checkRepTyCon (\tc -> tyConUnique tc `elem` keys)
1263 \end{code}
1264
1265 ----------------------------------------------
1266 These chaps do the work; they are not exported
1267 ----------------------------------------------
1268
1269 \begin{code}
1270 legalFEArgTyCon :: TyCon -> Bool
1271 legalFEArgTyCon tc
1272   -- It's illegal to make foreign exports that take unboxed
1273   -- arguments.  The RTS API currently can't invoke such things.  --SDM 7/2000
1274   = boxedMarshalableTyCon tc
1275
1276 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
1277 legalFIResultTyCon dflags tc
1278   | tc == unitTyCon         = True
1279   | otherwise               = marshalableTyCon dflags tc
1280
1281 legalFEResultTyCon :: TyCon -> Bool
1282 legalFEResultTyCon tc
1283   | tc == unitTyCon         = True
1284   | otherwise               = boxedMarshalableTyCon tc
1285
1286 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
1287 -- Checks validity of types going from Haskell -> external world
1288 legalOutgoingTyCon dflags _ tc
1289   = marshalableTyCon dflags tc
1290
1291 legalFFITyCon :: TyCon -> Bool
1292 -- True for any TyCon that can possibly be an arg or result of an FFI call
1293 legalFFITyCon tc
1294   = isUnLiftedTyCon tc || boxedMarshalableTyCon tc || tc == unitTyCon
1295
1296 marshalableTyCon :: DynFlags -> TyCon -> Bool
1297 marshalableTyCon dflags tc
1298   =  (dopt Opt_UnliftedFFITypes dflags 
1299       && isUnLiftedTyCon tc
1300       && not (isUnboxedTupleTyCon tc)
1301       && case tyConPrimRep tc of        -- Note [Marshalling VoidRep]
1302            VoidRep -> False
1303            _       -> True)
1304   || boxedMarshalableTyCon tc
1305
1306 boxedMarshalableTyCon :: TyCon -> Bool
1307 boxedMarshalableTyCon tc
1308    = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
1309                          , int32TyConKey, int64TyConKey
1310                          , wordTyConKey, word8TyConKey, word16TyConKey
1311                          , word32TyConKey, word64TyConKey
1312                          , floatTyConKey, doubleTyConKey
1313                          , ptrTyConKey, funPtrTyConKey
1314                          , charTyConKey
1315                          , stablePtrTyConKey
1316                          , boolTyConKey
1317                          ]
1318 \end{code}
1319
1320 Note [Marshalling VoidRep]
1321 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1322 We don't treat State# (whose PrimRep is VoidRep) as marshalable.
1323 In turn that means you can't write
1324         foreign import foo :: Int -> State# RealWorld
1325
1326 Reason: the back end falls over with panic "primRepHint:VoidRep";
1327         and there is no compelling reason to permit it