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