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