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