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