fix some coercion kind representation things, extend exprIsConApp_maybe to non-vanilla
[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 "typechechecker", 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, synTyConDefn, tyConUnique )
173 import Coercion         ( splitForAllCo_maybe )
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   | PatSkol DataCon     -- An existential type variable bound by a pattern for
348             SrcSpan     -- a data constructor with an existential type. E.g.
349                         --      data T = forall a. Eq a => MkT a
350                         --      f (MkT x) = ...
351                         -- The pattern MkT x will allocate an existential type
352                         -- variable for 'a'.  
353   | ArrowSkol SrcSpan   -- An arrow form (see TcArrows)
354
355   | GenSkol [TcTyVar]   -- Bound when doing a subsumption check for 
356             TcType      --      (forall tvs. ty)
357             SrcSpan
358
359   | UnkSkol             -- Unhelpful info (until I improve it)
360
361 -------------------------------------
362 -- UserTypeCtxt describes the places where a 
363 -- programmer-written type signature can occur
364 data UserTypeCtxt 
365   = FunSigCtxt Name     -- Function type signature
366                         -- Also used for types in SPECIALISE pragmas
367   | ExprSigCtxt         -- Expression type signature
368   | ConArgCtxt Name     -- Data constructor argument
369   | TySynCtxt Name      -- RHS of a type synonym decl
370   | GenPatCtxt          -- Pattern in generic decl
371                         --      f{| a+b |} (Inl x) = ...
372   | LamPatSigCtxt               -- Type sig in lambda pattern
373                         --      f (x::t) = ...
374   | BindPatSigCtxt      -- Type sig in pattern binding pattern
375                         --      (x::t, y) = e
376   | ResSigCtxt          -- Result type sig
377                         --      f x :: t = ....
378   | ForSigCtxt Name     -- Foreign inport or export signature
379   | RuleSigCtxt Name    -- Signature on a forall'd variable in a RULE
380   | DefaultDeclCtxt     -- Types in a default declaration
381   | SpecInstCtxt        -- SPECIALISE instance pragma
382
383 -- Notes re TySynCtxt
384 -- We allow type synonyms that aren't types; e.g.  type List = []
385 --
386 -- If the RHS mentions tyvars that aren't in scope, we'll 
387 -- quantify over them:
388 --      e.g.    type T = a->a
389 -- will become  type T = forall a. a->a
390 --
391 -- With gla-exts that's right, but for H98 we should complain. 
392
393 ---------------------------------
394 -- Kind variables:
395
396 mkKindName :: Unique -> Name
397 mkKindName unique = mkSystemName unique kind_var_occ
398
399 kindVarRef :: KindVar -> IORef MetaDetails
400 kindVarRef tc = 
401   case tcTyVarDetails tc of
402     MetaTv TauTv ref -> ref
403     other            -> pprPanic "kindVarRef" (ppr tc)
404
405 mkKindVar :: Unique -> IORef MetaDetails -> KindVar
406 mkKindVar u r 
407   = mkTcTyVar (mkKindName u)
408               tySuperKind  -- not sure this is right,
409                             -- do we need kind vars for
410                             -- coercions?
411               (MetaTv TauTv r)
412
413 kind_var_occ :: OccName -- Just one for all KindVars
414                         -- They may be jiggled by tidying
415 kind_var_occ = mkOccName tvName "k"
416 \end{code}
417 \end{code}
418
419 %************************************************************************
420 %*                                                                      *
421                 Pretty-printing
422 %*                                                                      *
423 %************************************************************************
424
425 \begin{code}
426 pprTcTyVarDetails :: TcTyVarDetails -> SDoc
427 -- For debugging
428 pprTcTyVarDetails (SkolemTv _)         = ptext SLIT("sk")
429 pprTcTyVarDetails (MetaTv BoxTv _)     = ptext SLIT("box")
430 pprTcTyVarDetails (MetaTv TauTv _)     = ptext SLIT("tau")
431 pprTcTyVarDetails (MetaTv (SigTv _) _) = ptext SLIT("sig")
432
433 pprUserTypeCtxt :: UserTypeCtxt -> SDoc
434 pprUserTypeCtxt (FunSigCtxt n)  = ptext SLIT("the type signature for") <+> quotes (ppr n)
435 pprUserTypeCtxt ExprSigCtxt     = ptext SLIT("an expression type signature")
436 pprUserTypeCtxt (ConArgCtxt c)  = ptext SLIT("the type of the constructor") <+> quotes (ppr c)
437 pprUserTypeCtxt (TySynCtxt c)   = ptext SLIT("the RHS of the type synonym") <+> quotes (ppr c)
438 pprUserTypeCtxt GenPatCtxt      = ptext SLIT("the type pattern of a generic definition")
439 pprUserTypeCtxt LamPatSigCtxt   = ptext SLIT("a pattern type signature")
440 pprUserTypeCtxt BindPatSigCtxt  = ptext SLIT("a pattern type signature")
441 pprUserTypeCtxt ResSigCtxt      = ptext SLIT("a result type signature")
442 pprUserTypeCtxt (ForSigCtxt n)  = ptext SLIT("the foreign declaration for") <+> quotes (ppr n)
443 pprUserTypeCtxt (RuleSigCtxt n) = ptext SLIT("the type signature for") <+> quotes (ppr n)
444 pprUserTypeCtxt DefaultDeclCtxt = ptext SLIT("a type in a `default' declaration")
445 pprUserTypeCtxt SpecInstCtxt    = ptext SLIT("a SPECIALISE instance pragma")
446
447
448 --------------------------------
449 tidySkolemTyVar :: TidyEnv -> TcTyVar -> (TidyEnv, TcTyVar)
450 -- Tidy the type inside a GenSkol, preparatory to printing it
451 tidySkolemTyVar env tv
452   = ASSERT( isSkolemTyVar tv || isSigTyVar tv )
453     (env1, mkTcTyVar (tyVarName tv) (tyVarKind tv) info1)
454   where
455     (env1, info1) = case tcTyVarDetails tv of
456                         SkolemTv info -> (env1, SkolemTv info')
457                                 where
458                                   (env1, info') = tidy_skol_info env info
459                         MetaTv (SigTv info) box -> (env1, MetaTv (SigTv info') box)
460                                 where
461                                   (env1, info') = tidy_skol_info env info
462                         info -> (env, info)
463
464     tidy_skol_info env (GenSkol tvs ty loc) = (env2, GenSkol tvs1 ty1 loc)
465                             where
466                               (env1, tvs1) = tidyOpenTyVars env tvs
467                               (env2, ty1)  = tidyOpenType env1 ty
468     tidy_skol_info env info = (env, info)
469                      
470 pprSkolTvBinding :: TcTyVar -> SDoc
471 -- Print info about the binding of a skolem tyvar, 
472 -- or nothing if we don't have anything useful to say
473 pprSkolTvBinding tv
474   = ppr_details (tcTyVarDetails tv)
475   where
476     ppr_details (MetaTv TauTv _)   = quotes (ppr tv) <+> ptext SLIT("is a meta type variable")
477     ppr_details (MetaTv BoxTv _)   = quotes (ppr tv) <+> ptext SLIT("is a boxy type variable")
478     ppr_details (MetaTv (SigTv info) _) = ppr_skol info
479     ppr_details (SkolemTv info)         = ppr_skol info
480
481     ppr_skol UnkSkol         = empty    -- Unhelpful; omit
482     ppr_skol (SigSkol ctxt)  = sep [quotes (ppr tv) <+> ptext SLIT("is bound by") <+> pprUserTypeCtxt ctxt,
483                                     nest 2 (ptext SLIT("at") <+> ppr (getSrcLoc tv))]
484     ppr_skol info            = quotes (ppr tv) <+> pprSkolInfo info
485  
486 pprSkolInfo :: SkolemInfo -> SDoc
487 pprSkolInfo (SigSkol ctxt)   = ptext SLIT("is bound by") <+> pprUserTypeCtxt ctxt
488 pprSkolInfo (ClsSkol cls)    = ptext SLIT("is bound by the class declaration for") <+> quotes (ppr cls)
489 pprSkolInfo (InstSkol df)    = ptext SLIT("is bound by the instance declaration at") <+> ppr (getSrcLoc df)
490 pprSkolInfo (ArrowSkol loc)  = ptext SLIT("is bound by the arrow form at") <+> ppr loc
491 pprSkolInfo (PatSkol dc loc) = sep [ptext SLIT("is bound by the pattern for") <+> quotes (ppr dc),
492                                     nest 2 (ptext SLIT("at") <+> ppr loc)]
493 pprSkolInfo (GenSkol tvs ty loc) = sep [sep [ptext SLIT("is bound by the polymorphic type"), 
494                                              nest 2 (quotes (ppr (mkForAllTys tvs ty)))],
495                                         nest 2 (ptext SLIT("at") <+> ppr loc)]
496 -- UnkSkol, SigSkol
497 -- For type variables the others are dealt with by pprSkolTvBinding.  
498 -- For Insts, these cases should not happen
499 pprSkolInfo UnkSkol = panic "UnkSkol"
500
501 instance Outputable MetaDetails where
502   ppr Flexi         = ptext SLIT("Flexi")
503   ppr (Indirect ty) = ptext SLIT("Indirect") <+> ppr ty
504 \end{code}
505
506
507 %************************************************************************
508 %*                                                                      *
509                 Predicates
510 %*                                                                      *
511 %************************************************************************
512
513 \begin{code}
514 isImmutableTyVar, isSkolemTyVar, isExistentialTyVar, isBoxyTyVar, isMetaTyVar :: TyVar -> Bool
515 isImmutableTyVar tv
516   | isTcTyVar tv = isSkolemTyVar tv
517   | otherwise    = True
518
519 isSkolemTyVar tv 
520   = ASSERT( isTcTyVar tv )
521     case tcTyVarDetails tv of
522         SkolemTv _         -> True
523         MetaTv _ _         -> False
524
525 isExistentialTyVar tv   -- Existential type variable, bound by a pattern
526   = ASSERT( isTcTyVar tv )
527     case tcTyVarDetails tv of
528         SkolemTv (PatSkol _ _) -> True
529         other                  -> False
530
531 isMetaTyVar tv 
532   = ASSERT2( isTcTyVar tv, ppr tv )
533     case tcTyVarDetails tv of
534         MetaTv _ _ -> True
535         other      -> False
536
537 isBoxyTyVar tv 
538   = ASSERT( isTcTyVar tv )
539     case tcTyVarDetails tv of
540         MetaTv BoxTv _ -> True
541         other          -> False
542
543 isSigTyVar tv 
544   = ASSERT( isTcTyVar tv )
545     case tcTyVarDetails tv of
546         MetaTv (SigTv _) _ -> True
547         other              -> False
548
549 metaTvRef :: TyVar -> IORef MetaDetails
550 metaTvRef tv 
551   = ASSERT( isTcTyVar tv )
552     case tcTyVarDetails tv of
553         MetaTv _ ref -> ref
554         other      -> pprPanic "metaTvRef" (ppr tv)
555
556 isFlexi, isIndirect :: MetaDetails -> Bool
557 isFlexi Flexi = True
558 isFlexi other = False
559
560 isIndirect (Indirect _) = True
561 isIndirect other        = False
562 \end{code}
563
564
565 %************************************************************************
566 %*                                                                      *
567 \subsection{Tau, sigma and rho}
568 %*                                                                      *
569 %************************************************************************
570
571 \begin{code}
572 mkSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
573 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
574
575 mkPhiTy :: [PredType] -> Type -> Type
576 mkPhiTy theta ty = foldr (\p r -> FunTy (mkPredTy p) r) ty theta
577 \end{code}
578
579 @isTauTy@ tests for nested for-alls.  It should not be called on a boxy type.
580
581 \begin{code}
582 isTauTy :: Type -> Bool
583 isTauTy ty | Just ty' <- tcView ty = isTauTy ty'
584 isTauTy (TyVarTy tv)     = ASSERT( not (isTcTyVar tv && isBoxyTyVar tv) )
585                            True
586 isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc
587 isTauTy (AppTy a b)       = isTauTy a && isTauTy b
588 isTauTy (FunTy a b)       = isTauTy a && isTauTy b
589 isTauTy (PredTy p)        = True                -- Don't look through source types
590 isTauTy other             = False
591
592
593 isTauTyCon :: TyCon -> Bool
594 -- Returns False for type synonyms whose expansion is a polytype
595 isTauTyCon tc | isSynTyCon tc = isTauTy (snd (synTyConDefn tc))
596               | otherwise     = True
597
598 ---------------
599 isBoxyTy :: TcType -> Bool
600 isBoxyTy ty = any isBoxyTyVar (varSetElems (tcTyVarsOfType ty))
601
602 isRigidTy :: TcType -> Bool
603 -- A type is rigid if it has no meta type variables in it
604 isRigidTy ty = all isSkolemTyVar (varSetElems (tcTyVarsOfType ty))
605
606 isRefineableTy :: TcType -> Bool
607 -- A type should have type refinements applied to it if it has
608 -- free type variables, and they are all rigid
609 isRefineableTy ty = not (null tc_tvs) && all isSkolemTyVar tc_tvs
610                     where
611                       tc_tvs = varSetElems (tcTyVarsOfType ty)
612
613 ---------------
614 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to 
615                                 -- construct a dictionary function name
616 getDFunTyKey ty | Just ty' <- tcView ty = getDFunTyKey ty'
617 getDFunTyKey (TyVarTy tv)    = getOccName tv
618 getDFunTyKey (TyConApp tc _) = getOccName tc
619 getDFunTyKey (AppTy fun _)   = getDFunTyKey fun
620 getDFunTyKey (FunTy arg _)   = getOccName funTyCon
621 getDFunTyKey (ForAllTy _ t)  = getDFunTyKey t
622 getDFunTyKey ty              = pprPanic "getDFunTyKey" (pprType ty)
623 -- PredTy shouldn't happen
624 \end{code}
625
626
627 %************************************************************************
628 %*                                                                      *
629 \subsection{Expanding and splitting}
630 %*                                                                      *
631 %************************************************************************
632
633 These tcSplit functions are like their non-Tc analogues, but
634         a) they do not look through newtypes
635         b) they do not look through PredTys
636         c) [future] they ignore usage-type annotations
637
638 However, they are non-monadic and do not follow through mutable type
639 variables.  It's up to you to make sure this doesn't matter.
640
641 \begin{code}
642 tcSplitForAllTys :: Type -> ([TyVar], Type)
643 tcSplitForAllTys ty = split ty ty []
644    where
645      split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
646      split orig_ty (ForAllTy tv ty) tvs 
647        | not (isCoVar tv) = split ty ty (tv:tvs)
648      split orig_ty t                tvs = (reverse tvs, orig_ty)
649
650 tcIsForAllTy ty | Just ty' <- tcView ty = tcIsForAllTy ty'
651 tcIsForAllTy (ForAllTy tv ty) = True
652 tcIsForAllTy t                = False
653
654 tcSplitPhiTy :: Type -> (ThetaType, Type)
655 tcSplitPhiTy ty = split ty ty []
656  where
657   split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
658   split orig_ty (FunTy arg res) ts 
659         | Just p <- tcSplitPredTy_maybe arg = split res res (p:ts)
660   split orig_ty ty ts
661         | Just (p, ty') <- splitForAllCo_maybe ty = split ty' ty' (p:ts) 
662   split orig_ty ty              ts = (reverse ts, orig_ty)
663
664 tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
665 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
666                         (tvs, rho) -> case tcSplitPhiTy rho of
667                                         (theta, tau) -> (tvs, theta, tau)
668
669 -----------------------
670 tcMultiSplitSigmaTy
671         :: TcSigmaType
672         -> ( [([TyVar], ThetaType)],    -- forall as.C => forall bs.D
673              TcSigmaType)               -- The rest of the type
674
675 -- We need a loop here because we are now prepared to entertain
676 -- types like
677 --      f:: forall a. Eq a => forall b. Baz b => tau
678 -- We want to instantiate this to
679 --      f2::tau         {f2 = f1 b (Baz b), f1 = f a (Eq a)}
680
681 tcMultiSplitSigmaTy sigma
682   = case (tcSplitSigmaTy sigma) of
683         ([],[],ty) -> ([], sigma)
684         (tvs, theta, ty) -> case tcMultiSplitSigmaTy ty of
685                                 (pairs, rest) -> ((tvs,theta):pairs, rest)
686
687 -----------------------
688 tcTyConAppTyCon :: Type -> TyCon
689 tcTyConAppTyCon ty = fst (tcSplitTyConApp ty)
690
691 tcTyConAppArgs :: Type -> [Type]
692 tcTyConAppArgs ty = snd (tcSplitTyConApp ty)
693
694 tcSplitTyConApp :: Type -> (TyCon, [Type])
695 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
696                         Just stuff -> stuff
697                         Nothing    -> pprPanic "tcSplitTyConApp" (pprType ty)
698
699 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
700 tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty'
701 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
702 tcSplitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
703         -- Newtypes are opaque, so they may be split
704         -- However, predicates are not treated
705         -- as tycon applications by the type checker
706 tcSplitTyConApp_maybe other             = Nothing
707
708 -----------------------
709 tcSplitFunTys :: Type -> ([Type], Type)
710 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
711                         Nothing        -> ([], ty)
712                         Just (arg,res) -> (arg:args, res')
713                                        where
714                                           (args,res') = tcSplitFunTys res
715
716 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
717 tcSplitFunTy_maybe ty | Just ty' <- tcView ty = tcSplitFunTy_maybe ty'
718 tcSplitFunTy_maybe (FunTy arg res)  = Just (arg, res)
719 tcSplitFunTy_maybe other            = Nothing
720
721 tcSplitFunTysN
722         :: TcRhoType 
723         -> Arity                -- N: Number of desired args
724         -> ([TcSigmaType],      -- Arg types (N or fewer)
725             TcSigmaType)        -- The rest of the type
726
727 tcSplitFunTysN ty n_args
728   | n_args == 0
729   = ([], ty)
730   | Just (arg,res) <- tcSplitFunTy_maybe ty
731   = case tcSplitFunTysN res (n_args - 1) of
732         (args, res) -> (arg:args, res)
733   | otherwise
734   = ([], ty)
735
736 tcSplitFunTy  ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
737 tcFunArgTy    ty = fst (tcSplitFunTy ty)
738 tcFunResultTy ty = snd (tcSplitFunTy ty)
739
740 -----------------------
741 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
742 tcSplitAppTy_maybe ty | Just ty' <- tcView ty = tcSplitAppTy_maybe ty'
743 tcSplitAppTy_maybe ty = repSplitAppTy_maybe ty
744
745 tcSplitAppTy :: Type -> (Type, Type)
746 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
747                     Just stuff -> stuff
748                     Nothing    -> pprPanic "tcSplitAppTy" (pprType ty)
749
750 tcSplitAppTys :: Type -> (Type, [Type])
751 tcSplitAppTys ty
752   = go ty []
753   where
754     go ty args = case tcSplitAppTy_maybe ty of
755                    Just (ty', arg) -> go ty' (arg:args)
756                    Nothing         -> (ty,args)
757
758 -----------------------
759 tcGetTyVar_maybe :: Type -> Maybe TyVar
760 tcGetTyVar_maybe ty | Just ty' <- tcView ty = tcGetTyVar_maybe ty'
761 tcGetTyVar_maybe (TyVarTy tv)   = Just tv
762 tcGetTyVar_maybe other          = Nothing
763
764 tcGetTyVar :: String -> Type -> TyVar
765 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
766
767 tcIsTyVarTy :: Type -> Bool
768 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
769
770 -----------------------
771 tcSplitDFunTy :: Type -> ([TyVar], [PredType], Class, [Type])
772 -- Split the type of a dictionary function
773 tcSplitDFunTy ty 
774   = case tcSplitSigmaTy ty   of { (tvs, theta, tau) ->
775     case tcSplitDFunHead tau of { (clas, tys) -> 
776     (tvs, theta, clas, tys) }}
777
778 tcSplitDFunHead :: Type -> (Class, [Type])
779 tcSplitDFunHead tau  
780   = case tcSplitPredTy_maybe tau of 
781         Just (ClassP clas tys) -> (clas, tys)
782         other -> panic "tcSplitDFunHead"
783
784 tcValidInstHeadTy :: Type -> Bool
785 -- Used in Haskell-98 mode, for the argument types of an instance head
786 -- These must not be type synonyms, but everywhere else type synonyms
787 -- are transparent, so we need a special function here
788 tcValidInstHeadTy ty
789   = case ty of
790         NoteTy _ ty     -> tcValidInstHeadTy ty
791         TyConApp tc tys -> not (isSynTyCon tc) && ok tys
792         FunTy arg res   -> ok [arg, res]
793         other           -> False
794   where
795         -- Check that all the types are type variables,
796         -- and that each is distinct
797     ok tys = equalLength tvs tys && hasNoDups tvs
798            where
799              tvs = mapCatMaybes get_tv tys
800
801     get_tv (NoteTy _ ty) = get_tv ty    -- Again, do not look
802     get_tv (TyVarTy tv)  = Just tv      -- through synonyms
803     get_tv other         = Nothing
804 \end{code}
805
806
807
808 %************************************************************************
809 %*                                                                      *
810 \subsection{Predicate types}
811 %*                                                                      *
812 %************************************************************************
813
814 \begin{code}
815 tcSplitPredTy_maybe :: Type -> Maybe PredType
816    -- Returns Just for predicates only
817 tcSplitPredTy_maybe ty | Just ty' <- tcView ty = tcSplitPredTy_maybe ty'
818 tcSplitPredTy_maybe (PredTy p)    = Just p
819 tcSplitPredTy_maybe other         = Nothing
820         
821 predTyUnique :: PredType -> Unique
822 predTyUnique (IParam n _)      = getUnique (ipNameName n)
823 predTyUnique (ClassP clas tys) = getUnique clas
824
825 mkPredName :: Unique -> SrcLoc -> PredType -> Name
826 mkPredName uniq loc (ClassP cls tys) = mkInternalName uniq (mkDictOcc (getOccName cls)) loc
827 mkPredName uniq loc (IParam ip ty)   = mkInternalName uniq (getOccName (ipNameName ip)) loc
828 \end{code}
829
830
831 --------------------- Dictionary types ---------------------------------
832
833 \begin{code}
834 mkClassPred clas tys = ClassP clas tys
835
836 isClassPred :: PredType -> Bool
837 isClassPred (ClassP clas tys) = True
838 isClassPred other             = False
839
840 isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
841 isTyVarClassPred other             = False
842
843 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
844 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
845 getClassPredTys_maybe _                 = Nothing
846
847 getClassPredTys :: PredType -> (Class, [Type])
848 getClassPredTys (ClassP clas tys) = (clas, tys)
849 getClassPredTys other = panic "getClassPredTys"
850
851 isEqPred :: PredType -> Bool
852 isEqPred (EqPred {}) = True
853 isEqPred _           = False
854
855 mkDictTy :: Class -> [Type] -> Type
856 mkDictTy clas tys = mkPredTy (ClassP clas tys)
857
858 isDictTy :: Type -> Bool
859 isDictTy ty | Just ty' <- tcView ty = isDictTy ty'
860 isDictTy (PredTy p) = isClassPred p
861 isDictTy other      = False
862 \end{code}
863
864 --------------------- Implicit parameters ---------------------------------
865
866 \begin{code}
867 isIPPred :: PredType -> Bool
868 isIPPred (IParam _ _) = True
869 isIPPred other        = False
870
871 isInheritablePred :: PredType -> Bool
872 -- Can be inherited by a context.  For example, consider
873 --      f x = let g y = (?v, y+x)
874 --            in (g 3 with ?v = 8, 
875 --                g 4 with ?v = 9)
876 -- The point is that g's type must be quantifed over ?v:
877 --      g :: (?v :: a) => a -> a
878 -- but it doesn't need to be quantified over the Num a dictionary
879 -- which can be free in g's rhs, and shared by both calls to g
880 isInheritablePred (ClassP _ _) = True
881 isInheritablePred other      = False
882
883 isLinearPred :: TcPredType -> Bool
884 isLinearPred (IParam (Linear n) _) = True
885 isLinearPred other                 = False
886 \end{code}
887
888 --------------------- Equality predicates ---------------------------------
889 \begin{code}
890 substEqSpec :: TvSubst -> [(TyVar,Type)] -> [(TcType,TcType)]
891 substEqSpec subst eq_spec = [ (substTyVar subst tv, substTy subst ty)
892                             | (tv,ty) <- eq_spec]
893 \end{code}
894
895 --------------------- The stupid theta (sigh) ---------------------------------
896
897 \begin{code}
898 dataConsStupidTheta :: [DataCon] -> ThetaType
899 -- Union the stupid thetas from all the specified constructors (non-empty)
900 -- All the constructors should have the same result type, modulo alpha conversion
901 -- The resulting ThetaType uses type variables from the *first* constructor in the list
902 --
903 -- It's here because it's used in MkId.mkRecordSelId, and in TcExpr
904 dataConsStupidTheta (con1:cons)
905   = nubBy tcEqPred all_preds
906   where
907     all_preds     = dataConStupidTheta con1 ++ other_stupids
908     res_tys1      = dataConResTys con1
909     tvs1          = tyVarsOfTypes res_tys1
910     other_stupids = [ substPred subst pred
911                     | con <- cons
912                     , let Just subst = tcMatchTys tvs1 res_tys1 (dataConResTys con)
913                     , pred <- dataConStupidTheta con ]
914 dataConsStupidTheta [] = panic "dataConsStupidTheta"
915 \end{code}
916
917
918 %************************************************************************
919 %*                                                                      *
920 \subsection{Predicates}
921 %*                                                                      *
922 %************************************************************************
923
924 isSigmaTy returns true of any qualified type.  It doesn't *necessarily* have 
925 any foralls.  E.g.
926         f :: (?x::Int) => Int -> Int
927
928 \begin{code}
929 isSigmaTy :: Type -> Bool
930 isSigmaTy ty | Just ty' <- tcView ty = isSigmaTy ty'
931 isSigmaTy (ForAllTy tyvar ty) = True
932 isSigmaTy (FunTy a b)         = isPredTy a
933 isSigmaTy _                   = False
934
935 isOverloadedTy :: Type -> Bool
936 isOverloadedTy ty | Just ty' <- tcView ty = isOverloadedTy ty'
937 isOverloadedTy (ForAllTy tyvar ty) = isOverloadedTy ty
938 isOverloadedTy (FunTy a b)         = isPredTy a
939 isOverloadedTy _                   = False
940
941 isPredTy :: Type -> Bool        -- Belongs in TcType because it does 
942                                 -- not look through newtypes, or predtypes (of course)
943 isPredTy ty | Just ty' <- tcView ty = isPredTy ty'
944 isPredTy (PredTy sty)  = True
945 isPredTy _             = False
946 \end{code}
947
948 \begin{code}
949 isFloatTy      = is_tc floatTyConKey
950 isDoubleTy     = is_tc doubleTyConKey
951 isIntegerTy    = is_tc integerTyConKey
952 isIntTy        = is_tc intTyConKey
953 isBoolTy       = is_tc boolTyConKey
954 isUnitTy       = is_tc unitTyConKey
955
956 is_tc :: Unique -> Type -> Bool
957 -- Newtypes are opaque to this
958 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
959                         Just (tc, _) -> uniq == getUnique tc
960                         Nothing      -> False
961 \end{code}
962
963
964 %************************************************************************
965 %*                                                                      *
966 \subsection{Misc}
967 %*                                                                      *
968 %************************************************************************
969
970 \begin{code}
971 deNoteType :: Type -> Type
972 -- Remove all *outermost* type synonyms and other notes
973 deNoteType ty | Just ty' <- tcView ty = deNoteType ty'
974 deNoteType ty = ty
975 \end{code}
976
977 \begin{code}
978 tcTyVarsOfType :: Type -> TcTyVarSet
979 -- Just the *TcTyVars* free in the type
980 -- (Types.tyVarsOfTypes finds all free TyVars)
981 tcTyVarsOfType (TyVarTy tv)         = if isTcTyVar tv then unitVarSet tv
982                                                       else emptyVarSet
983 tcTyVarsOfType (TyConApp tycon tys) = tcTyVarsOfTypes tys
984 tcTyVarsOfType (NoteTy _ ty)        = tcTyVarsOfType ty
985 tcTyVarsOfType (PredTy sty)         = tcTyVarsOfPred sty
986 tcTyVarsOfType (FunTy arg res)      = tcTyVarsOfType arg `unionVarSet` tcTyVarsOfType res
987 tcTyVarsOfType (AppTy fun arg)      = tcTyVarsOfType fun `unionVarSet` tcTyVarsOfType arg
988 tcTyVarsOfType (ForAllTy tyvar ty)  = tcTyVarsOfType ty `delVarSet` tyvar
989         -- We do sometimes quantify over skolem TcTyVars
990
991 tcTyVarsOfTypes :: [Type] -> TyVarSet
992 tcTyVarsOfTypes tys = foldr (unionVarSet.tcTyVarsOfType) emptyVarSet tys
993
994 tcTyVarsOfPred :: PredType -> TyVarSet
995 tcTyVarsOfPred (IParam _ ty)    = tcTyVarsOfType ty
996 tcTyVarsOfPred (ClassP _ tys)   = tcTyVarsOfTypes tys
997 tcTyVarsOfPred (EqPred ty1 ty2) = tcTyVarsOfType ty1 `unionVarSet` tcTyVarsOfType ty2
998 \end{code}
999
1000 Note [Silly type synonym]
1001 ~~~~~~~~~~~~~~~~~~~~~~~~~
1002 Consider
1003         type T a = Int
1004 What are the free tyvars of (T x)?  Empty, of course!  
1005 Here's the example that Ralf Laemmel showed me:
1006         foo :: (forall a. C u a -> C u a) -> u
1007         mappend :: Monoid u => u -> u -> u
1008
1009         bar :: Monoid u => u
1010         bar = foo (\t -> t `mappend` t)
1011 We have to generalise at the arg to f, and we don't
1012 want to capture the constraint (Monad (C u a)) because
1013 it appears to mention a.  Pretty silly, but it was useful to him.
1014
1015 exactTyVarsOfType is used by the type checker to figure out exactly
1016 which type variables are mentioned in a type.  It's also used in the
1017 smart-app checking code --- see TcExpr.tcIdApp
1018
1019 \begin{code}
1020 exactTyVarsOfType :: TcType -> TyVarSet
1021 -- Find the free type variables (of any kind)
1022 -- but *expand* type synonyms.  See Note [Silly type synonym] above.
1023 exactTyVarsOfType ty
1024   = go ty
1025   where
1026     go ty | Just ty' <- tcView ty = go ty'      -- This is the key line
1027     go (TyVarTy tv)               = unitVarSet tv
1028     go (TyConApp tycon tys)       = exactTyVarsOfTypes tys
1029     go (PredTy ty)                = go_pred ty
1030     go (FunTy arg res)            = go arg `unionVarSet` go res
1031     go (AppTy fun arg)            = go fun `unionVarSet` go arg
1032     go (ForAllTy tyvar ty)        = delVarSet (go ty) tyvar
1033
1034     go_pred (IParam _ ty)    = go ty
1035     go_pred (ClassP _ tys)   = exactTyVarsOfTypes tys
1036     go_pred (EqPred ty1 ty2) = go ty1 `unionVarSet` go ty2
1037
1038 exactTyVarsOfTypes :: [TcType] -> TyVarSet
1039 exactTyVarsOfTypes tys = foldr (unionVarSet . exactTyVarsOfType) emptyVarSet tys
1040 \end{code}
1041
1042 Find the free tycons and classes of a type.  This is used in the front
1043 end of the compiler.
1044
1045 \begin{code}
1046 tyClsNamesOfType :: Type -> NameSet
1047 tyClsNamesOfType (TyVarTy tv)               = emptyNameSet
1048 tyClsNamesOfType (TyConApp tycon tys)       = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
1049 tyClsNamesOfType (NoteTy _ ty2)             = tyClsNamesOfType ty2
1050 tyClsNamesOfType (PredTy (IParam n ty))     = tyClsNamesOfType ty
1051 tyClsNamesOfType (PredTy (ClassP cl tys))   = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
1052 tyClsNamesOfType (PredTy (EqPred ty1 ty2))  = tyClsNamesOfType ty1 `unionNameSets` tyClsNamesOfType ty2
1053 tyClsNamesOfType (FunTy arg res)            = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
1054 tyClsNamesOfType (AppTy fun arg)            = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
1055 tyClsNamesOfType (ForAllTy tyvar ty)        = tyClsNamesOfType ty
1056
1057 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
1058
1059 tyClsNamesOfDFunHead :: Type -> NameSet
1060 -- Find the free type constructors and classes 
1061 -- of the head of the dfun instance type
1062 -- The 'dfun_head_type' is because of
1063 --      instance Foo a => Baz T where ...
1064 -- The decl is an orphan if Baz and T are both not locally defined,
1065 --      even if Foo *is* locally defined
1066 tyClsNamesOfDFunHead dfun_ty 
1067   = case tcSplitSigmaTy dfun_ty of
1068         (tvs,_,head_ty) -> tyClsNamesOfType head_ty
1069
1070 classesOfTheta :: ThetaType -> [Class]
1071 -- Looks just for ClassP things; maybe it should check
1072 classesOfTheta preds = [ c | ClassP c _ <- preds ]
1073 \end{code}
1074
1075
1076 %************************************************************************
1077 %*                                                                      *
1078 \subsection[TysWiredIn-ext-type]{External types}
1079 %*                                                                      *
1080 %************************************************************************
1081
1082 The compiler's foreign function interface supports the passing of a
1083 restricted set of types as arguments and results (the restricting factor
1084 being the )
1085
1086 \begin{code}
1087 tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type)
1088 -- (isIOType t) returns (Just (IO,t')) if t is of the form (IO t'), or
1089 --                                     some newtype wrapping thereof
1090 --              returns Nothing otherwise
1091 tcSplitIOType_maybe ty 
1092   | Just (io_tycon, [io_res_ty]) <- tcSplitTyConApp_maybe ty,
1093         -- This split absolutely has to be a tcSplit, because we must
1094         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
1095     io_tycon `hasKey` ioTyConKey
1096   = Just (io_tycon, io_res_ty)
1097
1098   | Just ty' <- coreView ty     -- Look through non-recursive newtypes
1099   = tcSplitIOType_maybe ty'
1100
1101   | otherwise
1102   = Nothing
1103
1104 isFFITy :: Type -> Bool
1105 -- True for any TyCon that can possibly be an arg or result of an FFI call
1106 isFFITy ty = checkRepTyCon legalFFITyCon ty
1107
1108 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
1109 -- Checks for valid argument type for a 'foreign import'
1110 isFFIArgumentTy dflags safety ty 
1111    = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
1112
1113 isFFIExternalTy :: Type -> Bool
1114 -- Types that are allowed as arguments of a 'foreign export'
1115 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
1116
1117 isFFIImportResultTy :: DynFlags -> Type -> Bool
1118 isFFIImportResultTy dflags ty 
1119   = checkRepTyCon (legalFIResultTyCon dflags) ty
1120
1121 isFFIExportResultTy :: Type -> Bool
1122 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
1123
1124 isFFIDynArgumentTy :: Type -> Bool
1125 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
1126 -- or a newtype of either.
1127 isFFIDynArgumentTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1128
1129 isFFIDynResultTy :: Type -> Bool
1130 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
1131 -- or a newtype of either.
1132 isFFIDynResultTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1133
1134 isFFILabelTy :: Type -> Bool
1135 -- The type of a foreign label must be Ptr, FunPtr, Addr,
1136 -- or a newtype of either.
1137 isFFILabelTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1138
1139 isFFIDotnetTy :: DynFlags -> Type -> Bool
1140 isFFIDotnetTy dflags ty
1141   = checkRepTyCon (\ tc -> (legalFIResultTyCon dflags tc || 
1142                            isFFIDotnetObjTy ty || isStringTy ty)) ty
1143
1144 -- Support String as an argument or result from a .NET FFI call.
1145 isStringTy ty = 
1146   case tcSplitTyConApp_maybe (repType ty) of
1147     Just (tc, [arg_ty])
1148       | tc == listTyCon ->
1149         case tcSplitTyConApp_maybe (repType arg_ty) of
1150           Just (cc,[]) -> cc == charTyCon
1151           _ -> False
1152     _ -> False
1153
1154 -- Support String as an argument or result from a .NET FFI call.
1155 isFFIDotnetObjTy ty = 
1156   let
1157    (_, t_ty) = tcSplitForAllTys ty
1158   in
1159   case tcSplitTyConApp_maybe (repType t_ty) of
1160     Just (tc, [arg_ty]) | getName tc == objectTyConName -> True
1161     _ -> False
1162
1163 toDNType :: Type -> DNType
1164 toDNType ty
1165   | isStringTy ty = DNString
1166   | isFFIDotnetObjTy ty = DNObject
1167   | Just (tc,argTys) <- tcSplitTyConApp_maybe ty 
1168   =  case lookup (getUnique tc) dn_assoc of
1169        Just x  -> x
1170        Nothing 
1171          | tc `hasKey` ioTyConKey -> toDNType (head argTys)
1172          | otherwise -> pprPanic ("toDNType: unsupported .NET type") 
1173                           (pprType ty <+> parens (hcat (map pprType argTys)) <+> ppr tc)
1174   | otherwise = panic "toDNType"        -- Is this right?
1175     where
1176       dn_assoc :: [ (Unique, DNType) ]
1177       dn_assoc = [ (unitTyConKey,   DNUnit)
1178                  , (intTyConKey,    DNInt)
1179                  , (int8TyConKey,   DNInt8)
1180                  , (int16TyConKey,  DNInt16)
1181                  , (int32TyConKey,  DNInt32)
1182                  , (int64TyConKey,  DNInt64)
1183                  , (wordTyConKey,   DNInt)
1184                  , (word8TyConKey,  DNWord8)
1185                  , (word16TyConKey, DNWord16)
1186                  , (word32TyConKey, DNWord32)
1187                  , (word64TyConKey, DNWord64)
1188                  , (floatTyConKey,  DNFloat)
1189                  , (doubleTyConKey, DNDouble)
1190                  , (ptrTyConKey,    DNPtr)
1191                  , (funPtrTyConKey, DNPtr)
1192                  , (charTyConKey,   DNChar)
1193                  , (boolTyConKey,   DNBool)
1194                  ]
1195
1196 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
1197         -- Look through newtypes
1198         -- Non-recursive ones are transparent to splitTyConApp,
1199         -- but recursive ones aren't.  Manuel had:
1200         --      newtype T = MkT (Ptr T)
1201         -- and wanted it to work...
1202 checkRepTyCon check_tc ty 
1203   | Just (tc,_) <- splitTyConApp_maybe (repType ty) = check_tc tc
1204   | otherwise                                       = False
1205
1206 checkRepTyConKey :: [Unique] -> Type -> Bool
1207 -- Like checkRepTyCon, but just looks at the TyCon key
1208 checkRepTyConKey keys
1209   = checkRepTyCon (\tc -> tyConUnique tc `elem` keys)
1210 \end{code}
1211
1212 ----------------------------------------------
1213 These chaps do the work; they are not exported
1214 ----------------------------------------------
1215
1216 \begin{code}
1217 legalFEArgTyCon :: TyCon -> Bool
1218 legalFEArgTyCon tc
1219   -- It's illegal to make foreign exports that take unboxed
1220   -- arguments.  The RTS API currently can't invoke such things.  --SDM 7/2000
1221   = boxedMarshalableTyCon tc
1222
1223 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
1224 legalFIResultTyCon dflags tc
1225   | tc == unitTyCon         = True
1226   | otherwise               = marshalableTyCon dflags tc
1227
1228 legalFEResultTyCon :: TyCon -> Bool
1229 legalFEResultTyCon tc
1230   | tc == unitTyCon         = True
1231   | otherwise               = boxedMarshalableTyCon tc
1232
1233 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
1234 -- Checks validity of types going from Haskell -> external world
1235 legalOutgoingTyCon dflags safety tc
1236   = marshalableTyCon dflags tc
1237
1238 legalFFITyCon :: TyCon -> Bool
1239 -- True for any TyCon that can possibly be an arg or result of an FFI call
1240 legalFFITyCon tc
1241   = isUnLiftedTyCon tc || boxedMarshalableTyCon tc || tc == unitTyCon
1242
1243 marshalableTyCon dflags tc
1244   =  (dopt Opt_GlasgowExts dflags && isUnLiftedTyCon tc)
1245   || boxedMarshalableTyCon tc
1246
1247 boxedMarshalableTyCon tc
1248    = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
1249                          , int32TyConKey, int64TyConKey
1250                          , wordTyConKey, word8TyConKey, word16TyConKey
1251                          , word32TyConKey, word64TyConKey
1252                          , floatTyConKey, doubleTyConKey
1253                          , ptrTyConKey, funPtrTyConKey
1254                          , charTyConKey
1255                          , stablePtrTyConKey
1256                          , boolTyConKey
1257                          ]
1258 \end{code}