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