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