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