Make -fdicts-cheap cope with implication constraints
[ghc-hetmet.git] / compiler / typecheck / TcType.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[TcType]{Types used in the typechecker}
6
7 This module provides the Type interface for front-end parts of the 
8 compiler.  These parts 
9
10         * treat "source types" as opaque: 
11                 newtypes, and predicates are meaningful. 
12         * look through usage types
13
14 The "tc" prefix is for "TypeChecker", because the type checker
15 is the principal client.
16
17 \begin{code}
18 module TcType (
19   --------------------------------
20   -- Types 
21   TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType, 
22   TcTyVar, TcTyVarSet, TcKind, 
23
24   BoxyTyVar, BoxySigmaType, BoxyRhoType, BoxyThetaType, BoxyType,
25
26   --------------------------------
27   -- MetaDetails
28   UserTypeCtxt(..), pprUserTypeCtxt,
29   TcTyVarDetails(..), BoxInfo(..), pprTcTyVarDetails,
30   MetaDetails(Flexi, Indirect), SkolemInfo(..), pprSkolTvBinding, pprSkolInfo,
31   isImmutableTyVar, isSkolemTyVar, isMetaTyVar, isBoxyTyVar, 
32   isSigTyVar, isExistentialTyVar,  isTyConableTyVar,
33   metaTvRef, 
34   isFlexi, isIndirect, isRuntimeUnk, isUnk,
35
36   --------------------------------
37   -- Builders
38   mkPhiTy, mkSigmaTy, 
39
40   --------------------------------
41   -- Splitters  
42   -- These are important because they do not look through newtypes
43   tcView,
44   tcSplitForAllTys, tcSplitPhiTy, tcSplitPredFunTy_maybe,
45   tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy, tcSplitFunTysN,
46   tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
47   tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, repSplitAppTy_maybe,
48   tcInstHeadTyNotSynonym, tcInstHeadTyAppAllTyVars,
49   tcGetTyVar_maybe, tcGetTyVar,
50   tcSplitSigmaTy, tcMultiSplitSigmaTy, 
51
52   ---------------------------------
53   -- Predicates. 
54   -- Again, newtypes are opaque
55   tcEqType, tcEqTypes, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred, tcEqTypeX,
56   eqKind, 
57   isSigmaTy, isOverloadedTy, isRigidTy, isBoxyTy,
58   isDoubleTy, isFloatTy, isIntTy, isWordTy, isStringTy,
59   isIntegerTy, isBoolTy, isUnitTy, isCharTy,
60   isTauTy, isTauTyCon, tcIsTyVarTy, tcIsForAllTy, 
61   isOpenSynTyConApp,
62
63   ---------------------------------
64   -- Misc type manipulators
65   deNoteType,
66   tyClsNamesOfType, tyClsNamesOfDFunHead, 
67   getDFunTyKey,
68
69   ---------------------------------
70   -- Predicate types  
71   getClassPredTys_maybe, getClassPredTys, 
72   isClassPred, isTyVarClassPred, isEqPred, 
73   mkDictTy, tcSplitPredTy_maybe, 
74   isPredTy, isDictTy, isDictLikeTy,
75   tcSplitDFunTy, tcSplitDFunHead, predTyUnique, 
76   mkClassPred, isInheritablePred, isIPPred, 
77   dataConsStupidTheta, isRefineableTy, isRefineablePred,
78
79   ---------------------------------
80   -- Foreign import and export
81   isFFIArgumentTy,     -- :: DynFlags -> Safety -> Type -> Bool
82   isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
83   isFFIExportResultTy, -- :: Type -> Bool
84   isFFIExternalTy,     -- :: Type -> Bool
85   isFFIDynArgumentTy,  -- :: Type -> Bool
86   isFFIDynResultTy,    -- :: Type -> Bool
87   isFFILabelTy,        -- :: Type -> Bool
88   isFFIDotnetTy,       -- :: DynFlags -> Type -> Bool
89   isFFIDotnetObjTy,    -- :: Type -> Bool
90   isFFITy,             -- :: Type -> Bool
91   isFunPtrTy,          -- :: Type -> Bool
92   tcSplitIOType_maybe, -- :: Type -> Maybe Type  
93   toDNType,            -- :: Type -> DNType
94
95   --------------------------------
96   -- Rexported from Type
97   Kind,         -- Stuff to do with kinds is insensitive to pre/post Tc
98   unliftedTypeKind, liftedTypeKind, argTypeKind,
99   openTypeKind, mkArrowKind, mkArrowKinds, 
100   isLiftedTypeKind, isUnliftedTypeKind, isSubOpenTypeKind, 
101   isSubArgTypeKind, isSubKind, defaultKind,
102   kindVarRef, mkKindVar,  
103
104   Type, PredType(..), ThetaType, 
105   mkForAllTy, mkForAllTys, 
106   mkFunTy, mkFunTys, zipFunTys, 
107   mkTyConApp, mkAppTy, mkAppTys, applyTy, applyTys,
108   mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys, 
109
110   -- Type substitutions
111   TvSubst(..),  -- Representation visible to a few friends
112   TvSubstEnv, emptyTvSubst, substEqSpec,
113   mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
114   getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope, lookupTyVar,
115   extendTvSubst, extendTvSubstList, isInScope, mkTvSubst, zipTyEnv,
116   substTy, substTys, substTyWith, substTheta, substTyVar, substTyVars, substTyVarBndr,
117
118   isUnLiftedType,       -- Source types are always lifted
119   isUnboxedTupleType,   -- Ditto
120   isPrimitiveType, 
121
122   tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
123   tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars, tidySkolemTyVar,
124   typeKind, tidyKind,
125
126   tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
127   tcTyVarsOfType, tcTyVarsOfTypes, exactTyVarsOfType, exactTyVarsOfTypes,
128
129   pprKind, pprParendKind,
130   pprType, pprParendType, pprTypeApp, pprTyThingCategory,
131   pprPred, pprTheta, pprThetaArrow, pprClassPred
132
133   ) where
134
135 #include "HsVersions.h"
136
137 -- friends:
138 import TypeRep
139 import DataCon
140 import Class
141 import Var
142 import ForeignCall
143 import Unify
144 import VarSet
145 import Type
146 import Coercion
147 import TyCon
148
149 -- others:
150 import DynFlags
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( isTcTyVar tv && (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   = ASSERT2( isTcTyVar tv, ppr 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 tcSplitPredFunTy_maybe :: Type -> Maybe (PredType, Type)
665 -- Split off the first predicate argument from a type
666 tcSplitPredFunTy_maybe ty | Just ty' <- tcView ty = tcSplitPredFunTy_maybe ty'
667 tcSplitPredFunTy_maybe (ForAllTy tv ty)
668   | isCoVar tv = Just (coVarPred tv, ty)
669 tcSplitPredFunTy_maybe (FunTy arg res)
670   | Just p <- tcSplitPredTy_maybe arg = Just (p, res)
671 tcSplitPredFunTy_maybe _
672   = Nothing
673
674 tcSplitPhiTy :: Type -> (ThetaType, Type)
675 tcSplitPhiTy ty
676   = split ty []
677   where
678     split ty ts 
679       = case tcSplitPredFunTy_maybe ty of
680           Just (pred, ty) -> split ty (pred:ts)
681           Nothing         -> (reverse ts, ty)
682
683 tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
684 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
685                         (tvs, rho) -> case tcSplitPhiTy rho of
686                                         (theta, tau) -> (tvs, theta, tau)
687
688 -----------------------
689 tcMultiSplitSigmaTy
690         :: TcSigmaType
691         -> ( [([TyVar], ThetaType)],    -- forall as.C => forall bs.D
692              TcSigmaType)               -- The rest of the type
693
694 -- We need a loop here because we are now prepared to entertain
695 -- types like
696 --      f:: forall a. Eq a => forall b. Baz b => tau
697 -- We want to instantiate this to
698 --      f2::tau         {f2 = f1 b (Baz b), f1 = f a (Eq a)}
699
700 tcMultiSplitSigmaTy sigma
701   = case (tcSplitSigmaTy sigma) of
702         ([], [], _) -> ([], sigma)
703         (tvs, theta, ty) -> case tcMultiSplitSigmaTy ty of
704                                 (pairs, rest) -> ((tvs,theta):pairs, rest)
705
706 -----------------------
707 tcTyConAppTyCon :: Type -> TyCon
708 tcTyConAppTyCon ty = case tcSplitTyConApp_maybe ty of
709                         Just (tc, _) -> tc
710                         Nothing      -> pprPanic "tcTyConAppTyCon" (pprType ty)
711
712 tcTyConAppArgs :: Type -> [Type]
713 tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of
714                         Just (_, args) -> args
715                         Nothing        -> pprPanic "tcTyConAppArgs" (pprType ty)
716
717 tcSplitTyConApp :: Type -> (TyCon, [Type])
718 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
719                         Just stuff -> stuff
720                         Nothing    -> pprPanic "tcSplitTyConApp" (pprType ty)
721
722 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
723 tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty'
724 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
725 tcSplitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
726         -- Newtypes are opaque, so they may be split
727         -- However, predicates are not treated
728         -- as tycon applications by the type checker
729 tcSplitTyConApp_maybe _                 = Nothing
730
731 -----------------------
732 tcSplitFunTys :: Type -> ([Type], Type)
733 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
734                         Nothing        -> ([], ty)
735                         Just (arg,res) -> (arg:args, res')
736                                        where
737                                           (args,res') = tcSplitFunTys res
738
739 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
740 tcSplitFunTy_maybe ty | Just ty' <- tcView ty           = tcSplitFunTy_maybe ty'
741 tcSplitFunTy_maybe (FunTy arg res) | not (isPredTy arg) = Just (arg, res)
742 tcSplitFunTy_maybe _                                    = Nothing
743         -- Note the (not (isPredTy arg)) guard
744         -- Consider     (?x::Int) => Bool
745         -- We don't want to treat this as a function type!
746         -- A concrete example is test tc230:
747         --      f :: () -> (?p :: ()) => () -> ()
748         --
749         --      g = f () ()
750
751 tcSplitFunTysN
752         :: TcRhoType 
753         -> Arity                -- N: Number of desired args
754         -> ([TcSigmaType],      -- Arg types (N or fewer)
755             TcSigmaType)        -- The rest of the type
756
757 tcSplitFunTysN ty n_args
758   | n_args == 0
759   = ([], ty)
760   | Just (arg,res) <- tcSplitFunTy_maybe ty
761   = case tcSplitFunTysN res (n_args - 1) of
762         (args, res) -> (arg:args, res)
763   | otherwise
764   = ([], ty)
765
766 tcSplitFunTy :: Type -> (Type, Type)
767 tcSplitFunTy  ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
768
769 tcFunArgTy :: Type -> Type
770 tcFunArgTy    ty = fst (tcSplitFunTy ty)
771
772 tcFunResultTy :: Type -> Type
773 tcFunResultTy ty = snd (tcSplitFunTy ty)
774
775 -----------------------
776 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
777 tcSplitAppTy_maybe ty | Just ty' <- tcView ty = tcSplitAppTy_maybe ty'
778 tcSplitAppTy_maybe ty = repSplitAppTy_maybe ty
779
780 tcSplitAppTy :: Type -> (Type, Type)
781 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
782                     Just stuff -> stuff
783                     Nothing    -> pprPanic "tcSplitAppTy" (pprType ty)
784
785 tcSplitAppTys :: Type -> (Type, [Type])
786 tcSplitAppTys ty
787   = go ty []
788   where
789     go ty args = case tcSplitAppTy_maybe ty of
790                    Just (ty', arg) -> go ty' (arg:args)
791                    Nothing         -> (ty,args)
792
793 -----------------------
794 tcGetTyVar_maybe :: Type -> Maybe TyVar
795 tcGetTyVar_maybe ty | Just ty' <- tcView ty = tcGetTyVar_maybe ty'
796 tcGetTyVar_maybe (TyVarTy tv)   = Just tv
797 tcGetTyVar_maybe _              = Nothing
798
799 tcGetTyVar :: String -> Type -> TyVar
800 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
801
802 tcIsTyVarTy :: Type -> Bool
803 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
804
805 -----------------------
806 tcSplitDFunTy :: Type -> ([TyVar], [PredType], Class, [Type])
807 -- Split the type of a dictionary function
808 tcSplitDFunTy ty 
809   = case tcSplitSigmaTy ty   of { (tvs, theta, tau) ->
810     case tcSplitDFunHead tau of { (clas, tys) -> 
811     (tvs, theta, clas, tys) }}
812
813 tcSplitDFunHead :: Type -> (Class, [Type])
814 tcSplitDFunHead tau  
815   = case tcSplitPredTy_maybe tau of 
816         Just (ClassP clas tys) -> (clas, tys)
817         _ -> panic "tcSplitDFunHead"
818
819 tcInstHeadTyNotSynonym :: Type -> Bool
820 -- Used in Haskell-98 mode, for the argument types of an instance head
821 -- These must not be type synonyms, but everywhere else type synonyms
822 -- are transparent, so we need a special function here
823 tcInstHeadTyNotSynonym ty
824   = case ty of
825         TyConApp tc _ -> not (isSynTyCon tc)
826         _ -> True
827
828 tcInstHeadTyAppAllTyVars :: Type -> Bool
829 -- Used in Haskell-98 mode, for the argument types of an instance head
830 -- These must be a constructor applied to type variable arguments
831 tcInstHeadTyAppAllTyVars ty
832   = case ty of
833         TyConApp _ tys  -> ok tys
834         FunTy arg res   -> ok [arg, res]
835         _               -> False
836   where
837         -- Check that all the types are type variables,
838         -- and that each is distinct
839     ok tys = equalLength tvs tys && hasNoDups tvs
840            where
841              tvs = mapCatMaybes get_tv tys
842
843     get_tv (TyVarTy tv)  = Just tv      -- through synonyms
844     get_tv _             = Nothing
845 \end{code}
846
847
848
849 %************************************************************************
850 %*                                                                      *
851 \subsection{Predicate types}
852 %*                                                                      *
853 %************************************************************************
854
855 \begin{code}
856 tcSplitPredTy_maybe :: Type -> Maybe PredType
857    -- Returns Just for predicates only
858 tcSplitPredTy_maybe ty | Just ty' <- tcView ty = tcSplitPredTy_maybe ty'
859 tcSplitPredTy_maybe (PredTy p)    = Just p
860 tcSplitPredTy_maybe _             = Nothing
861
862 predTyUnique :: PredType -> Unique
863 predTyUnique (IParam n _)    = getUnique (ipNameName n)
864 predTyUnique (ClassP clas _) = getUnique clas
865 predTyUnique (EqPred a b)    = pprPanic "predTyUnique" (ppr (EqPred a b))
866 \end{code}
867
868
869 --------------------- Dictionary types ---------------------------------
870
871 \begin{code}
872 mkClassPred :: Class -> [Type] -> PredType
873 mkClassPred clas tys = ClassP clas tys
874
875 isClassPred :: PredType -> Bool
876 isClassPred (ClassP _ _) = True
877 isClassPred _            = False
878
879 isTyVarClassPred :: PredType -> Bool
880 isTyVarClassPred (ClassP _ tys) = all tcIsTyVarTy tys
881 isTyVarClassPred _              = False
882
883 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
884 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
885 getClassPredTys_maybe _                 = Nothing
886
887 getClassPredTys :: PredType -> (Class, [Type])
888 getClassPredTys (ClassP clas tys) = (clas, tys)
889 getClassPredTys _ = panic "getClassPredTys"
890
891 mkDictTy :: Class -> [Type] -> Type
892 mkDictTy clas tys = mkPredTy (ClassP clas tys)
893
894 isDictTy :: Type -> Bool
895 isDictTy ty | Just ty' <- tcView ty = isDictTy ty'
896 isDictTy (PredTy p) = isClassPred p
897 isDictTy _          = False
898
899 isDictLikeTy :: Type -> Bool
900 -- Note [Dictionary-like types]
901 isDictLikeTy ty | Just ty' <- tcView ty = isDictTy ty'
902 isDictLikeTy (PredTy p) = isClassPred p
903 isDictLikeTy (TyConApp tc tys) 
904   | isTupleTyCon tc     = all isDictLikeTy tys
905 isDictLikeTy _          = False
906 \end{code}
907
908 Note [Dictionary-like types]
909 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
910 Being "dictionary-like" means either a dictionary type or a tuple thereof.
911 In GHC 6.10 we build implication constraints which construct such tuples,
912 and if we land up with a binding
913     t :: (C [a], Eq [a])
914     t = blah
915 then we want to treat t as cheap under "-fdicts-cheap" for example.
916 (Implication constraints are normally inlined, but sadly not if the
917 occurrence is itself inside an INLINE function!  Until we revise the 
918 handling of implication constraints, that is.)  This turned out to
919 be important in getting good arities in DPH code.  Example:
920
921     class C a
922     class D a where { foo :: a -> a }
923     instance C a => D (Maybe a) where { foo x = x }
924
925     bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
926     {-# INLINE bar #-}
927     bar x y = (foo (Just x), foo (Just y))
928
929 Then 'bar' should jolly well have arity 4 (two dicts, two args), but
930 we ended up with something like
931    bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
932                                 in \x,y. <blah>)
933
934 This is all a bit ad-hoc; eg it relies on knowing that implication
935 constraints build tuples.
936
937 --------------------- Implicit parameters ---------------------------------
938
939 \begin{code}
940 isIPPred :: PredType -> Bool
941 isIPPred (IParam _ _) = True
942 isIPPred _            = False
943
944 isInheritablePred :: PredType -> Bool
945 -- Can be inherited by a context.  For example, consider
946 --      f x = let g y = (?v, y+x)
947 --            in (g 3 with ?v = 8, 
948 --                g 4 with ?v = 9)
949 -- The point is that g's type must be quantifed over ?v:
950 --      g :: (?v :: a) => a -> a
951 -- but it doesn't need to be quantified over the Num a dictionary
952 -- which can be free in g's rhs, and shared by both calls to g
953 isInheritablePred (ClassP _ _) = True
954 isInheritablePred (EqPred _ _) = True
955 isInheritablePred _            = False
956 \end{code}
957
958 --------------------- Equality predicates ---------------------------------
959 \begin{code}
960 substEqSpec :: TvSubst -> [(TyVar,Type)] -> [(TcType,TcType)]
961 substEqSpec subst eq_spec = [ (substTyVar subst tv, substTy subst ty)
962                             | (tv,ty) <- eq_spec]
963 \end{code}
964
965 --------------------- The stupid theta (sigh) ---------------------------------
966
967 \begin{code}
968 dataConsStupidTheta :: [DataCon] -> ThetaType
969 -- Union the stupid thetas from all the specified constructors (non-empty)
970 -- All the constructors should have the same result type, modulo alpha conversion
971 -- The resulting ThetaType uses type variables from the *first* constructor in the list
972 --
973 -- It's here because it's used in MkId.mkRecordSelId, and in TcExpr
974 dataConsStupidTheta (con1:cons)
975   = nubBy tcEqPred all_preds
976   where
977     all_preds     = dataConStupidTheta con1 ++ other_stupids
978     res_ty1       = dataConOrigResTy con1
979     other_stupids = [ substPred subst pred
980                     | con <- cons
981                     , let (tvs, _, _, res_ty) = dataConSig con
982                           Just subst = tcMatchTy (mkVarSet tvs) res_ty res_ty1
983                     , pred <- dataConStupidTheta con ]
984 dataConsStupidTheta [] = panic "dataConsStupidTheta"
985 \end{code}
986
987
988 %************************************************************************
989 %*                                                                      *
990 \subsection{Predicates}
991 %*                                                                      *
992 %************************************************************************
993
994 isSigmaTy returns true of any qualified type.  It doesn't *necessarily* have 
995 any foralls.  E.g.
996         f :: (?x::Int) => Int -> Int
997
998 \begin{code}
999 isSigmaTy :: Type -> Bool
1000 isSigmaTy ty | Just ty' <- tcView ty = isSigmaTy ty'
1001 isSigmaTy (ForAllTy _ _) = True
1002 isSigmaTy (FunTy a _)    = isPredTy a
1003 isSigmaTy _              = False
1004
1005 isOverloadedTy :: Type -> Bool
1006 -- Yes for a type of a function that might require evidence-passing
1007 -- Used only by bindInstsOfLocalFuns/Pats
1008 -- NB: be sure to check for type with an equality predicate; hence isCoVar
1009 isOverloadedTy ty | Just ty' <- tcView ty = isOverloadedTy ty'
1010 isOverloadedTy (ForAllTy tv ty) = isCoVar tv || isOverloadedTy ty
1011 isOverloadedTy (FunTy a _)      = isPredTy a
1012 isOverloadedTy _                = False
1013
1014 isPredTy :: Type -> Bool        -- Belongs in TcType because it does 
1015                                 -- not look through newtypes, or predtypes (of course)
1016 isPredTy ty | Just ty' <- tcView ty = isPredTy ty'
1017 isPredTy (PredTy _) = True
1018 isPredTy _          = False
1019 \end{code}
1020
1021 \begin{code}
1022 isFloatTy, isDoubleTy, isIntegerTy, isIntTy, isWordTy, isBoolTy,
1023     isUnitTy, isCharTy :: Type -> Bool
1024 isFloatTy      = is_tc floatTyConKey
1025 isDoubleTy     = is_tc doubleTyConKey
1026 isIntegerTy    = is_tc integerTyConKey
1027 isIntTy        = is_tc intTyConKey
1028 isWordTy       = is_tc wordTyConKey
1029 isBoolTy       = is_tc boolTyConKey
1030 isUnitTy       = is_tc unitTyConKey
1031 isCharTy       = is_tc charTyConKey
1032
1033 isStringTy :: Type -> Bool
1034 isStringTy ty
1035   = case tcSplitTyConApp_maybe ty of
1036       Just (tc, [arg_ty]) -> tc == listTyCon && isCharTy arg_ty
1037       _                   -> False
1038
1039 is_tc :: Unique -> Type -> Bool
1040 -- Newtypes are opaque to this
1041 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
1042                         Just (tc, _) -> uniq == getUnique tc
1043                         Nothing      -> False
1044 \end{code}
1045
1046 \begin{code}
1047 -- NB: Currently used in places where we have already expanded type synonyms;
1048 --     hence no 'coreView'.  This could, however, be changed without breaking
1049 --     any code.
1050 isOpenSynTyConApp :: TcTauType -> Bool
1051 isOpenSynTyConApp (TyConApp tc tys) = isOpenSynTyCon tc && 
1052                                       length tys == tyConArity tc 
1053 isOpenSynTyConApp _other            = False
1054 \end{code}
1055
1056
1057 %************************************************************************
1058 %*                                                                      *
1059 \subsection{Misc}
1060 %*                                                                      *
1061 %************************************************************************
1062
1063 \begin{code}
1064 deNoteType :: Type -> Type
1065 -- Remove all *outermost* type synonyms and other notes
1066 deNoteType ty | Just ty' <- tcView ty = deNoteType ty'
1067 deNoteType ty = ty
1068 \end{code}
1069
1070 \begin{code}
1071 tcTyVarsOfType :: Type -> TcTyVarSet
1072 -- Just the *TcTyVars* free in the type
1073 -- (Types.tyVarsOfTypes finds all free TyVars)
1074 tcTyVarsOfType (TyVarTy tv)         = if isTcTyVar tv then unitVarSet tv
1075                                                       else emptyVarSet
1076 tcTyVarsOfType (TyConApp _ tys)     = tcTyVarsOfTypes tys
1077 tcTyVarsOfType (PredTy sty)         = tcTyVarsOfPred sty
1078 tcTyVarsOfType (FunTy arg res)      = tcTyVarsOfType arg `unionVarSet` tcTyVarsOfType res
1079 tcTyVarsOfType (AppTy fun arg)      = tcTyVarsOfType fun `unionVarSet` tcTyVarsOfType arg
1080 tcTyVarsOfType (ForAllTy tyvar ty)  = (tcTyVarsOfType ty `delVarSet` tyvar)
1081                                       `unionVarSet` tcTyVarsOfTyVar tyvar
1082         -- We do sometimes quantify over skolem TcTyVars
1083
1084 tcTyVarsOfTyVar :: TcTyVar -> TyVarSet
1085 tcTyVarsOfTyVar tv | isCoVar tv = tcTyVarsOfType (tyVarKind tv)
1086                    | otherwise  = emptyVarSet
1087
1088 tcTyVarsOfTypes :: [Type] -> TyVarSet
1089 tcTyVarsOfTypes tys = foldr (unionVarSet.tcTyVarsOfType) emptyVarSet tys
1090
1091 tcTyVarsOfPred :: PredType -> TyVarSet
1092 tcTyVarsOfPred (IParam _ ty)    = tcTyVarsOfType ty
1093 tcTyVarsOfPred (ClassP _ tys)   = tcTyVarsOfTypes tys
1094 tcTyVarsOfPred (EqPred ty1 ty2) = tcTyVarsOfType ty1 `unionVarSet` tcTyVarsOfType ty2
1095 \end{code}
1096
1097 Note [Silly type synonym]
1098 ~~~~~~~~~~~~~~~~~~~~~~~~~
1099 Consider
1100         type T a = Int
1101 What are the free tyvars of (T x)?  Empty, of course!  
1102 Here's the example that Ralf Laemmel showed me:
1103         foo :: (forall a. C u a -> C u a) -> u
1104         mappend :: Monoid u => u -> u -> u
1105
1106         bar :: Monoid u => u
1107         bar = foo (\t -> t `mappend` t)
1108 We have to generalise at the arg to f, and we don't
1109 want to capture the constraint (Monad (C u a)) because
1110 it appears to mention a.  Pretty silly, but it was useful to him.
1111
1112 exactTyVarsOfType is used by the type checker to figure out exactly
1113 which type variables are mentioned in a type.  It's also used in the
1114 smart-app checking code --- see TcExpr.tcIdApp
1115
1116 On the other hand, consider a *top-level* definition
1117         f = (\x -> x) :: T a -> T a
1118 If we don't abstract over 'a' it'll get fixed to GHC.Prim.Any, and then
1119 if we have an application like (f "x") we get a confusing error message 
1120 involving Any.  So the conclusion is this: when generalising
1121   - at top level use tyVarsOfType
1122   - in nested bindings use exactTyVarsOfType
1123 See Trac #1813 for example.
1124
1125 \begin{code}
1126 exactTyVarsOfType :: TcType -> TyVarSet
1127 -- Find the free type variables (of any kind)
1128 -- but *expand* type synonyms.  See Note [Silly type synonym] above.
1129 exactTyVarsOfType ty
1130   = go ty
1131   where
1132     go ty | Just ty' <- tcView ty = go ty'      -- This is the key line
1133     go (TyVarTy tv)               = unitVarSet tv
1134     go (TyConApp _ tys)           = exactTyVarsOfTypes tys
1135     go (PredTy ty)                = go_pred ty
1136     go (FunTy arg res)            = go arg `unionVarSet` go res
1137     go (AppTy fun arg)            = go fun `unionVarSet` go arg
1138     go (ForAllTy tyvar ty)        = delVarSet (go ty) tyvar
1139                                     `unionVarSet` go_tv tyvar
1140
1141     go_pred (IParam _ ty)    = go ty
1142     go_pred (ClassP _ tys)   = exactTyVarsOfTypes tys
1143     go_pred (EqPred ty1 ty2) = go ty1 `unionVarSet` go ty2
1144
1145     go_tv tyvar | isCoVar tyvar = go (tyVarKind tyvar)
1146                 | otherwise     = emptyVarSet
1147
1148 exactTyVarsOfTypes :: [TcType] -> TyVarSet
1149 exactTyVarsOfTypes tys = foldr (unionVarSet . exactTyVarsOfType) emptyVarSet tys
1150 \end{code}
1151
1152 Find the free tycons and classes of a type.  This is used in the front
1153 end of the compiler.
1154
1155 \begin{code}
1156 tyClsNamesOfType :: Type -> NameSet
1157 tyClsNamesOfType (TyVarTy _)                = emptyNameSet
1158 tyClsNamesOfType (TyConApp tycon tys)       = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
1159 tyClsNamesOfType (PredTy (IParam _ ty))     = tyClsNamesOfType ty
1160 tyClsNamesOfType (PredTy (ClassP cl tys))   = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
1161 tyClsNamesOfType (PredTy (EqPred ty1 ty2))  = tyClsNamesOfType ty1 `unionNameSets` tyClsNamesOfType ty2
1162 tyClsNamesOfType (FunTy arg res)            = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
1163 tyClsNamesOfType (AppTy fun arg)            = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
1164 tyClsNamesOfType (ForAllTy _ ty)            = tyClsNamesOfType ty
1165
1166 tyClsNamesOfTypes :: [Type] -> NameSet
1167 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
1168
1169 tyClsNamesOfDFunHead :: Type -> NameSet
1170 -- Find the free type constructors and classes 
1171 -- of the head of the dfun instance type
1172 -- The 'dfun_head_type' is because of
1173 --      instance Foo a => Baz T where ...
1174 -- The decl is an orphan if Baz and T are both not locally defined,
1175 --      even if Foo *is* locally defined
1176 tyClsNamesOfDFunHead dfun_ty 
1177   = case tcSplitSigmaTy dfun_ty of
1178         (_, _, head_ty) -> tyClsNamesOfType head_ty
1179 \end{code}
1180
1181
1182 %************************************************************************
1183 %*                                                                      *
1184 \subsection[TysWiredIn-ext-type]{External types}
1185 %*                                                                      *
1186 %************************************************************************
1187
1188 The compiler's foreign function interface supports the passing of a
1189 restricted set of types as arguments and results (the restricting factor
1190 being the )
1191
1192 \begin{code}
1193 tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type, CoercionI)
1194 -- (isIOType t) returns Just (IO,t',co)
1195 --                              if co : t ~ IO t'
1196 --              returns Nothing otherwise
1197 tcSplitIOType_maybe ty 
1198   = case tcSplitTyConApp_maybe ty of
1199         -- This split absolutely has to be a tcSplit, because we must
1200         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
1201
1202         Just (io_tycon, [io_res_ty]) 
1203            |  io_tycon `hasKey` ioTyConKey 
1204            -> Just (io_tycon, io_res_ty, IdCo)
1205
1206         Just (tc, tys)
1207            | not (isRecursiveTyCon tc)
1208            , Just (ty, co1) <- instNewTyCon_maybe tc tys
1209                   -- Newtypes that require a coercion are ok
1210            -> case tcSplitIOType_maybe ty of
1211                 Nothing             -> Nothing
1212                 Just (tc, ty', co2) -> Just (tc, ty', co1 `mkTransCoI` co2)
1213
1214         _ -> Nothing
1215
1216 isFFITy :: Type -> Bool
1217 -- True for any TyCon that can possibly be an arg or result of an FFI call
1218 isFFITy ty = checkRepTyCon legalFFITyCon ty
1219
1220 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
1221 -- Checks for valid argument type for a 'foreign import'
1222 isFFIArgumentTy dflags safety ty 
1223    = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
1224
1225 isFFIExternalTy :: Type -> Bool
1226 -- Types that are allowed as arguments of a 'foreign export'
1227 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
1228
1229 isFFIImportResultTy :: DynFlags -> Type -> Bool
1230 isFFIImportResultTy dflags ty 
1231   = checkRepTyCon (legalFIResultTyCon dflags) ty
1232
1233 isFFIExportResultTy :: Type -> Bool
1234 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
1235
1236 isFFIDynArgumentTy :: Type -> Bool
1237 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
1238 -- or a newtype of either.
1239 isFFIDynArgumentTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1240
1241 isFFIDynResultTy :: Type -> Bool
1242 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
1243 -- or a newtype of either.
1244 isFFIDynResultTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1245
1246 isFFILabelTy :: Type -> Bool
1247 -- The type of a foreign label must be Ptr, FunPtr, Addr,
1248 -- or a newtype of either.
1249 isFFILabelTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1250
1251 isFFIDotnetTy :: DynFlags -> Type -> Bool
1252 isFFIDotnetTy dflags ty
1253   = checkRepTyCon (\ tc -> (legalFIResultTyCon dflags tc || 
1254                            isFFIDotnetObjTy ty || isStringTy ty)) ty
1255         -- NB: isStringTy used to look through newtypes, but
1256         --     it no longer does so.  May need to adjust isFFIDotNetTy
1257         --     if we do want to look through newtypes.
1258
1259 isFFIDotnetObjTy :: Type -> Bool
1260 isFFIDotnetObjTy ty
1261   = checkRepTyCon check_tc t_ty
1262   where
1263    (_, t_ty) = tcSplitForAllTys ty
1264    check_tc tc = getName tc == objectTyConName
1265
1266 isFunPtrTy :: Type -> Bool
1267 isFunPtrTy = checkRepTyConKey [funPtrTyConKey]
1268
1269 toDNType :: Type -> DNType
1270 toDNType ty
1271   | isStringTy ty = DNString
1272   | isFFIDotnetObjTy ty = DNObject
1273   | Just (tc,argTys) <- tcSplitTyConApp_maybe ty 
1274   =  case lookup (getUnique tc) dn_assoc of
1275        Just x  -> x
1276        Nothing 
1277          | tc `hasKey` ioTyConKey -> toDNType (head argTys)
1278          | otherwise -> pprPanic ("toDNType: unsupported .NET type") 
1279                           (pprType ty <+> parens (hcat (map pprType argTys)) <+> ppr tc)
1280   | otherwise = panic "toDNType"        -- Is this right?
1281     where
1282       dn_assoc :: [ (Unique, DNType) ]
1283       dn_assoc = [ (unitTyConKey,   DNUnit)
1284                  , (intTyConKey,    DNInt)
1285                  , (int8TyConKey,   DNInt8)
1286                  , (int16TyConKey,  DNInt16)
1287                  , (int32TyConKey,  DNInt32)
1288                  , (int64TyConKey,  DNInt64)
1289                  , (wordTyConKey,   DNInt)
1290                  , (word8TyConKey,  DNWord8)
1291                  , (word16TyConKey, DNWord16)
1292                  , (word32TyConKey, DNWord32)
1293                  , (word64TyConKey, DNWord64)
1294                  , (floatTyConKey,  DNFloat)
1295                  , (doubleTyConKey, DNDouble)
1296                  , (ptrTyConKey,    DNPtr)
1297                  , (funPtrTyConKey, DNPtr)
1298                  , (charTyConKey,   DNChar)
1299                  , (boolTyConKey,   DNBool)
1300                  ]
1301
1302 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
1303 -- Look through newtypes, but *not* foralls
1304 -- Should work even for recursive newtypes
1305 -- eg Manuel had:       newtype T = MkT (Ptr T)
1306 checkRepTyCon check_tc ty
1307   = go [] ty
1308   where
1309     go rec_nts ty
1310       | Just (tc,tys) <- splitTyConApp_maybe ty
1311       = case carefullySplitNewType_maybe rec_nts tc tys of
1312            Just (rec_nts', ty') -> go rec_nts' ty'
1313            Nothing              -> check_tc tc
1314       | otherwise
1315       = False
1316
1317 checkRepTyConKey :: [Unique] -> Type -> Bool
1318 -- Like checkRepTyCon, but just looks at the TyCon key
1319 checkRepTyConKey keys
1320   = checkRepTyCon (\tc -> tyConUnique tc `elem` keys)
1321 \end{code}
1322
1323 ----------------------------------------------
1324 These chaps do the work; they are not exported
1325 ----------------------------------------------
1326
1327 \begin{code}
1328 legalFEArgTyCon :: TyCon -> Bool
1329 legalFEArgTyCon tc
1330   -- It's illegal to make foreign exports that take unboxed
1331   -- arguments.  The RTS API currently can't invoke such things.  --SDM 7/2000
1332   = boxedMarshalableTyCon tc
1333
1334 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
1335 legalFIResultTyCon dflags tc
1336   | tc == unitTyCon         = True
1337   | otherwise               = marshalableTyCon dflags tc
1338
1339 legalFEResultTyCon :: TyCon -> Bool
1340 legalFEResultTyCon tc
1341   | tc == unitTyCon         = True
1342   | otherwise               = boxedMarshalableTyCon tc
1343
1344 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
1345 -- Checks validity of types going from Haskell -> external world
1346 legalOutgoingTyCon dflags _ tc
1347   = marshalableTyCon dflags tc
1348
1349 legalFFITyCon :: TyCon -> Bool
1350 -- True for any TyCon that can possibly be an arg or result of an FFI call
1351 legalFFITyCon tc
1352   = isUnLiftedTyCon tc || boxedMarshalableTyCon tc || tc == unitTyCon
1353
1354 marshalableTyCon :: DynFlags -> TyCon -> Bool
1355 marshalableTyCon dflags tc
1356   =  (dopt Opt_UnliftedFFITypes dflags 
1357       && isUnLiftedTyCon tc
1358       && not (isUnboxedTupleTyCon tc)
1359       && case tyConPrimRep tc of        -- Note [Marshalling VoidRep]
1360            VoidRep -> False
1361            _       -> True)
1362   || boxedMarshalableTyCon tc
1363
1364 boxedMarshalableTyCon :: TyCon -> Bool
1365 boxedMarshalableTyCon tc
1366    = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
1367                          , int32TyConKey, int64TyConKey
1368                          , wordTyConKey, word8TyConKey, word16TyConKey
1369                          , word32TyConKey, word64TyConKey
1370                          , floatTyConKey, doubleTyConKey
1371                          , ptrTyConKey, funPtrTyConKey
1372                          , charTyConKey
1373                          , stablePtrTyConKey
1374                          , boolTyConKey
1375                          ]
1376 \end{code}
1377
1378 Note [Marshalling VoidRep]
1379 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1380 We don't treat State# (whose PrimRep is VoidRep) as marshalable.
1381 In turn that means you can't write
1382         foreign import foo :: Int -> State# RealWorld
1383
1384 Reason: the back end falls over with panic "primRepHint:VoidRep";
1385         and there is no compelling reason to permit it