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