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