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