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