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