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