[project @ 1997-05-18 19:56:49 by sof]
[ghc-hetmet.git] / ghc / compiler / types / Type.lhs
1 \begin{code}
2 #include "HsVersions.h"
3
4 module Type (
5         GenType(..), SYN_IE(Type), SYN_IE(TauType),
6         mkTyVarTy, mkTyVarTys,
7         getTyVar, getTyVar_maybe, isTyVarTy,
8         mkAppTy, mkAppTys, splitAppTy, splitAppTys,
9         mkFunTy, mkFunTys,
10         splitFunTy, splitFunTyExpandingDicts, splitFunTyExpandingDictsAndPeeking,
11         getFunTy_maybe, getFunTyExpandingDicts_maybe,
12         mkTyConTy, getTyCon_maybe, applyTyCon,
13         mkSynTy,
14         mkForAllTy, mkForAllTys, getForAllTy_maybe, getForAllTyExpandingDicts_maybe, splitForAllTy,
15         mkForAllUsageTy, getForAllUsageTy,
16         applyTy,
17 #ifdef DEBUG
18         expandTy, -- only let out for debugging (ToDo: rm?)
19 #endif
20         isPrimType, isUnboxedType, typePrimRep,
21
22         SYN_IE(RhoType), SYN_IE(SigmaType), SYN_IE(ThetaType),
23         mkDictTy,
24         mkRhoTy, splitRhoTy, mkTheta, isDictTy,
25         mkSigmaTy, splitSigmaTy,
26
27         maybeAppTyCon, getAppTyCon,
28         maybeAppDataTyCon, getAppDataTyCon, getAppSpecDataTyCon,
29         maybeAppDataTyConExpandingDicts, maybeAppSpecDataTyConExpandingDicts,
30         getAppDataTyConExpandingDicts,  getAppSpecDataTyConExpandingDicts,
31         maybeBoxedPrimType,
32
33         matchTy, matchTys, eqTy, eqSimpleTy, eqSimpleTheta,
34
35         instantiateTy, instantiateTauTy, instantiateUsage,
36         applyTypeEnvToTy,
37
38         isTauTy,
39
40         tyVarsOfType, tyVarsOfTypes, namesOfType, typeKind,
41         showTypeCategory
42     ) where
43
44 IMP_Ubiq()
45 IMPORT_DELOOPER(IdLoop)  -- for paranoia checking
46 IMPORT_DELOOPER(TyLoop)
47 --IMPORT_DELOOPER(PrelLoop)  -- for paranoia checking
48
49 -- friends:
50 import Class    --( classSig, classOpLocalType, GenClass{-instances-} )
51 import Kind     ( mkBoxedTypeKind, resultKind, notArrowKind, Kind )
52 import TyCon    ( mkFunTyCon, isFunTyCon, isEnumerationTyCon, isTupleTyCon, maybeTyConSingleCon,
53                   isPrimTyCon, isDataTyCon, isSynTyCon, maybeNewTyCon, isNewTyCon,
54                   tyConKind, tyConDataCons, getSynTyConDefn, TyCon )
55 import TyVar    ( tyVarKind, GenTyVar{-instances-}, SYN_IE(GenTyVarSet),
56                   emptyTyVarSet, unionTyVarSets, minusTyVarSet,
57                   unitTyVarSet, nullTyVarEnv, lookupTyVarEnv, delFromTyVarEnv,
58                   addOneToTyVarEnv, SYN_IE(TyVarEnv), SYN_IE(TyVar) )
59 import Usage    ( usageOmega, GenUsage, SYN_IE(Usage), SYN_IE(UVar), SYN_IE(UVarEnv),
60                   nullUVarEnv, addOneToUVarEnv, lookupUVarEnv, eqUVar,
61                   eqUsage )
62
63 import Name     ( NamedThing(..), 
64                   NameSet(..), unionNameSets, emptyNameSet, unitNameSet, minusNameSet
65                 )
66
67 -- others
68 import Maybes   ( maybeToBool, assocMaybe )
69 import PrimRep  ( PrimRep(..) )
70 import Unique   -- quite a few *Keys
71 import UniqFM   ( Uniquable(..) )
72 import Util     ( thenCmp, zipEqual, assoc,
73                   panic, panic#, assertPanic, pprPanic,
74                   Ord3(..){-instances-}
75                 )
76 -- ToDo:rm all these
77 --import        {-mumble-}
78 --      Pretty
79 --import  {-mumble-}
80 --      PprStyle
81 --import        {-mumble-}
82 --      PprType --(pprType )
83 --import PprEnv
84 \end{code}
85
86 Data types
87 ~~~~~~~~~~
88
89 \begin{code}
90 type Type  = GenType TyVar UVar -- Used after typechecker
91
92 data GenType tyvar uvar -- Parameterised over type and usage variables
93   = TyVarTy tyvar
94
95   | AppTy
96         (GenType tyvar uvar)
97         (GenType tyvar uvar)
98
99   | TyConTy     -- Constants of a specified kind
100         TyCon   -- Must *not* be a SynTyCon
101         (GenUsage uvar) -- Usage gives uvar of the full application,
102                         -- iff the full application is of kind Type
103                         -- c.f. the Usage field in TyVars
104
105   | SynTy       -- Synonyms must be saturated, and contain their expansion
106         TyCon   -- Must be a SynTyCon
107         [GenType tyvar uvar]
108         (GenType tyvar uvar)    -- Expansion!
109
110   | ForAllTy
111         tyvar
112         (GenType tyvar uvar)    -- TypeKind
113
114   | ForAllUsageTy
115         uvar                    -- Quantify over this
116         [uvar]                  -- Bounds; the quantified var must be
117                                 -- less than or equal to all these
118         (GenType tyvar uvar)
119
120         -- Two special cases that save a *lot* of administrative
121         -- overhead:
122
123   | FunTy                       -- BoxedTypeKind
124         (GenType tyvar uvar)    -- Both args are of TypeKind
125         (GenType tyvar uvar)
126         (GenUsage uvar)
127
128   | DictTy                      -- TypeKind
129         Class                   -- Class
130         (GenType tyvar uvar)    -- Arg has kind TypeKind
131         (GenUsage uvar)
132 \end{code}
133
134 \begin{code}
135 type RhoType   = Type
136 type TauType   = Type
137 type ThetaType = [(Class, Type)]
138 type SigmaType = Type
139 \end{code}
140
141
142 Notes on type synonyms
143 ~~~~~~~~~~~~~~~~~~~~~~
144 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
145 to return type synonyms whereever possible. Thus
146
147         type Foo a = a -> a
148
149 we want 
150         splitFunTys (a -> Foo a) = ([a], Foo a)
151 not                                ([a], a -> a)
152
153 The reason is that we then get better (shorter) type signatures in 
154 interfaces.  Notably this plays a role in tcTySigs in TcBinds.lhs.
155
156
157 Expand abbreviations
158 ~~~~~~~~~~~~~~~~~~~~
159 Removes just the top level of any abbreviations.
160
161 \begin{code}
162 expandTy :: Type -> Type        -- Restricted to Type due to Dict expansion
163
164 expandTy (FunTy t1 t2 u) = AppTy (AppTy (TyConTy mkFunTyCon u) t1) t2
165 expandTy (SynTy _  _  t) = expandTy t
166 expandTy (DictTy clas ty u)
167   = case all_arg_tys of
168
169         []       -> voidTy              -- Empty dictionary represented by Void
170
171         [arg_ty] -> expandTy arg_ty     -- just the <whatever> itself
172
173                 -- The extra expandTy is to make sure that
174                 -- the result isn't still a dict, which it might be
175                 -- if the original guy was a dict with one superdict and
176                 -- no methods!
177
178         other -> ASSERT(not (null all_arg_tys))
179                 foldl AppTy (TyConTy (tupleTyCon (length all_arg_tys)) u) all_arg_tys
180
181                 -- A tuple of 'em
182                 -- Note: length of all_arg_tys can be 0 if the class is
183                 --       CCallable, CReturnable (and anything else
184                 --       *really weird* that the user writes).
185   where
186     (tyvar, super_classes, ops) = classSig clas
187     super_dict_tys = map mk_super_ty super_classes
188     class_op_tys   = map mk_op_ty ops
189     all_arg_tys    = super_dict_tys ++ class_op_tys
190     mk_super_ty sc = DictTy sc ty usageOmega
191     mk_op_ty    op = instantiateTy [(tyvar,ty)] (classOpLocalType op)
192
193 expandTy ty = ty
194 \end{code}
195
196 Simple construction and analysis functions
197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 \begin{code}
199 mkTyVarTy  :: t   -> GenType t u
200 mkTyVarTys :: [t] -> [GenType t y]
201 mkTyVarTy  = TyVarTy
202 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
203
204 getTyVar :: String -> GenType t u -> t
205 getTyVar msg (TyVarTy tv)   = tv
206 getTyVar msg (SynTy _ _ t)  = getTyVar msg t
207 getTyVar msg other          = panic ("getTyVar: " ++ msg)
208
209 getTyVar_maybe :: GenType t u -> Maybe t
210 getTyVar_maybe (TyVarTy tv)  = Just tv
211 getTyVar_maybe (SynTy _ _ t) = getTyVar_maybe t
212 getTyVar_maybe other         = Nothing
213
214 isTyVarTy :: GenType t u -> Bool
215 isTyVarTy (TyVarTy tv)  = True
216 isTyVarTy (SynTy _ _ t) = isTyVarTy t
217 isTyVarTy other = False
218 \end{code}
219
220 \begin{code}
221 mkAppTy = AppTy
222
223 mkAppTys :: GenType t u -> [GenType t u] -> GenType t u
224 mkAppTys t ts = foldl AppTy t ts
225
226 splitAppTy :: GenType t u -> (GenType t u, GenType t u)
227 splitAppTy (AppTy t arg) = (t,arg)
228 splitAppTy (SynTy _ _ t) = splitAppTy t
229 splitAppTy other         = panic "splitAppTy"
230
231 splitAppTys :: GenType t u -> (GenType t u, [GenType t u])
232 splitAppTys t = go t []
233   where
234     go (AppTy t arg)     ts = go t (arg:ts)
235     go (FunTy fun arg u) ts = (TyConTy mkFunTyCon u, fun:arg:ts)
236     go (SynTy _ _ t)     ts = go t ts
237     go t                 ts = (t,ts)
238 \end{code}
239
240 \begin{code}
241 -- NB mkFunTy, mkFunTys puts in Omega usages, for now at least
242 mkFunTy arg res = FunTy arg res usageOmega
243
244 mkFunTys :: [GenType t u] -> GenType t u -> GenType t u
245 mkFunTys ts t = foldr (\ f a -> FunTy f a usageOmega) t ts
246
247   -- getFunTy_maybe and splitFunTy *must* have the general type given, which
248   -- means they *can't* do the DictTy jiggery-pokery that
249   -- *is* sometimes required.  Hence we also have the ExpandingDicts variants
250   -- The relationship between these
251   -- two functions is like that between eqTy and eqSimpleTy.
252   -- ToDo: NUKE when we do dicts via newtype
253
254 getFunTy_maybe :: GenType t u -> Maybe (GenType t u, GenType t u)
255 getFunTy_maybe t
256   = go t t
257   where 
258         -- See notes on type synonyms above
259     go syn_t (FunTy arg result _) = Just (arg,result)
260     go syn_t (AppTy (AppTy (TyConTy tycon _) arg) res)
261                  | isFunTyCon tycon = Just (arg, res)
262     go syn_t (SynTy _ _ t)          = go syn_t t
263     go syn_t other                  = Nothing
264
265 getFunTyExpandingDicts_maybe :: Bool -- True <=> peek inside newtype applicatons
266                              -> Type
267                              -> Maybe (Type, Type)
268
269 getFunTyExpandingDicts_maybe peek (FunTy arg result _) = Just (arg,result)
270 getFunTyExpandingDicts_maybe peek
271         (AppTy (AppTy (TyConTy tycon _) arg) res) | isFunTyCon tycon = Just (arg, res)
272 getFunTyExpandingDicts_maybe peek (SynTy _ _ t)     = getFunTyExpandingDicts_maybe peek t
273 getFunTyExpandingDicts_maybe peek ty@(DictTy _ _ _) = getFunTyExpandingDicts_maybe peek (expandTy ty)
274
275 getFunTyExpandingDicts_maybe True (ForAllTy _ ty)   = getFunTyExpandingDicts_maybe True ty
276         -- Ignore for-alls when peeking.  See note with defn of getFunTyExpandingDictsAndPeeking
277
278
279 {-      This is a truly disgusting bit of code. 
280         It's used by the code generator to look at the rep of a newtype.
281         The code gen will have thrown away coercions involving that newtype, so
282         this is the other side of the coin.
283         Gruesome in the extreme.
284 -}
285
286 getFunTyExpandingDicts_maybe peek other
287   | not peek = Nothing -- that was easy
288   | otherwise
289   = case (maybeAppTyCon other) of
290       Just (tc, arg_tys)
291         | isNewTyCon tc && not (null data_cons)
292         -> getFunTyExpandingDicts_maybe peek inside_ty
293         where
294           data_cons   = tyConDataCons tc
295           [the_con]   = data_cons
296           [inside_ty] = dataConArgTys the_con arg_tys
297
298       other -> Nothing
299
300
301 splitFunTy                         :: GenType t u -> ([GenType t u], GenType t u)
302 splitFunTyExpandingDicts           :: Type        -> ([Type], Type)
303 splitFunTyExpandingDictsAndPeeking :: Type        -> ([Type], Type)
304
305 splitFunTy                         t = split_fun_ty getFunTy_maybe                       t
306 splitFunTyExpandingDicts           t = split_fun_ty (getFunTyExpandingDicts_maybe False) t
307 splitFunTyExpandingDictsAndPeeking t = split_fun_ty (getFunTyExpandingDicts_maybe True)  t
308         -- This "peeking" stuff is used only by the code generator.
309         -- It's interested in the representation type of things, ignoring:
310         --      newtype         Why???  Nuked SLPJ May 97.  We may not know the 
311         --                      rep of an abstractly imported newtype
312         --      foralls
313         --      expanding dictionary reps
314         --      synonyms, of course
315
316 split_fun_ty get t = go t []
317   where
318     go t ts = case (get t) of
319                 Just (arg,res) -> go res (arg:ts)
320                 Nothing        -> (reverse ts, t)
321 \end{code}
322
323 \begin{code}
324 -- NB applyTyCon puts in usageOmega, for now at least
325 mkTyConTy tycon
326   = ASSERT(not (isSynTyCon tycon))
327     TyConTy tycon usageOmega
328
329 applyTyCon :: TyCon -> [GenType t u] -> GenType t u
330 applyTyCon tycon tys
331   = ASSERT (not (isSynTyCon tycon))
332     --(if (not (isSynTyCon tycon)) then \x->x else pprTrace "applyTyCon:" (pprTyCon PprDebug tycon)) $
333     foldl AppTy (TyConTy tycon usageOmega) tys
334
335 getTyCon_maybe               :: GenType t u -> Maybe TyCon
336 --getTyConExpandingDicts_maybe :: Type        -> Maybe TyCon
337
338 getTyCon_maybe (TyConTy tycon _) = Just tycon
339 getTyCon_maybe (SynTy _ _ t)     = getTyCon_maybe t
340 getTyCon_maybe other_ty          = Nothing
341
342 --getTyConExpandingDicts_maybe (TyConTy tycon _) = Just tycon
343 --getTyConExpandingDicts_maybe (SynTy _ _ t)     = getTyConExpandingDicts_maybe t
344 --getTyConExpandingDicts_maybe ty@(DictTy _ _ _) = getTyConExpandingDicts_maybe (expandTy ty)
345 --getTyConExpandingDicts_maybe other_ty        = Nothing
346 \end{code}
347
348 \begin{code}
349 mkSynTy syn_tycon tys
350   = ASSERT(isSynTyCon syn_tycon)
351     SynTy syn_tycon tys (instantiateTauTy (zipEqual "mkSynTy" tyvars tys) body)
352   where
353     (tyvars, body) = getSynTyConDefn syn_tycon
354 \end{code}
355
356 Tau stuff
357 ~~~~~~~~~
358 \begin{code}
359 isTauTy :: GenType t u -> Bool
360 isTauTy (TyVarTy v)        = True
361 isTauTy (TyConTy _ _)      = True
362 isTauTy (AppTy a b)        = isTauTy a && isTauTy b
363 isTauTy (FunTy a b _)      = isTauTy a && isTauTy b
364 isTauTy (SynTy _ _ ty)     = isTauTy ty
365 isTauTy other              = False
366 \end{code}
367
368 Rho stuff
369 ~~~~~~~~~
370 NB mkRhoTy and mkDictTy put in usageOmega, for now at least
371
372 \begin{code}
373 mkDictTy :: Class -> GenType t u -> GenType t u
374 mkDictTy clas ty = DictTy clas ty usageOmega
375
376 mkRhoTy :: [(Class, GenType t u)] -> GenType t u -> GenType t u
377 mkRhoTy theta ty =
378   foldr (\(c,t) r -> FunTy (DictTy c t usageOmega) r usageOmega) ty theta
379
380 splitRhoTy :: GenType t u -> ([(Class,GenType t u)], GenType t u)
381 splitRhoTy t =
382   go t t []
383  where
384         -- See notes on type synonyms above
385   go syn_t (FunTy (DictTy c t _) r _) ts = go r r ((c,t):ts)
386   go syn_t (AppTy (AppTy (TyConTy tycon _) (DictTy c t _)) r) ts
387         | isFunTyCon tycon
388         = go r r ((c,t):ts)
389   go syn_t (SynTy _ _ t) ts = go syn_t t ts
390   go syn_t t ts = (reverse ts, syn_t)
391
392
393 mkTheta :: [Type] -> ThetaType
394     -- recover a ThetaType from the types of some dictionaries
395 mkTheta dict_tys
396   = map cvt dict_tys
397   where
398     cvt (DictTy clas ty _) = (clas, ty)
399     cvt other              = panic "Type.mkTheta" -- pprPanic "mkTheta:" (pprType PprDebug other)
400
401 isDictTy (DictTy _ _ _) = True
402 isDictTy (SynTy  _ _ t) = isDictTy t
403 isDictTy _              = False
404 \end{code}
405
406
407 Forall stuff
408 ~~~~~~~~~~~~
409 \begin{code}
410 mkForAllTy = ForAllTy
411
412 mkForAllTys :: [t] -> GenType t u -> GenType t u
413 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
414
415 getForAllTy_maybe :: GenType t u -> Maybe (t,GenType t u)
416 getForAllTy_maybe (SynTy _ _ t)      = getForAllTy_maybe t
417 getForAllTy_maybe (ForAllTy tyvar t) = Just(tyvar,t)
418 getForAllTy_maybe _                  = Nothing
419
420 getForAllTyExpandingDicts_maybe :: Type -> Maybe (TyVar, Type)
421 getForAllTyExpandingDicts_maybe (SynTy _ _ t)      = getForAllTyExpandingDicts_maybe t
422 getForAllTyExpandingDicts_maybe (ForAllTy tyvar t) = Just(tyvar,t)
423 getForAllTyExpandingDicts_maybe ty@(DictTy _ _ _)  = getForAllTyExpandingDicts_maybe (expandTy ty)
424 getForAllTyExpandingDicts_maybe _                  = Nothing
425
426 splitForAllTy :: GenType t u-> ([t], GenType t u)
427 splitForAllTy t = go t t []
428                where
429                         -- See notes on type synonyms above
430                     go syn_t (ForAllTy tv t) tvs = go t t (tv:tvs)
431                     go syn_t (SynTy _ _ t)   tvs = go syn_t t tvs
432                     go syn_t t               tvs = (reverse tvs, syn_t)
433 \end{code}
434
435 \begin{code}
436 mkForAllUsageTy :: u -> [u] -> GenType t u -> GenType t u
437 mkForAllUsageTy = ForAllUsageTy
438
439 getForAllUsageTy :: GenType t u -> Maybe (u,[u],GenType t u)
440 getForAllUsageTy (ForAllUsageTy uvar bounds t) = Just(uvar,bounds,t)
441 getForAllUsageTy (SynTy _ _ t) = getForAllUsageTy t
442 getForAllUsageTy _ = Nothing
443 \end{code}
444
445 Applied tycons (includes FunTyCons)
446 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
447 \begin{code}
448 maybeAppTyCon
449         :: GenType tyvar uvar
450         -> Maybe (TyCon,                -- the type constructor
451                   [GenType tyvar uvar]) -- types to which it is applied
452
453 maybeAppTyCon ty
454   = case (getTyCon_maybe app_ty) of
455         Nothing    -> Nothing
456         Just tycon -> Just (tycon, arg_tys)
457   where
458     (app_ty, arg_tys) = splitAppTys ty
459
460
461 getAppTyCon
462         :: GenType tyvar uvar
463         -> (TyCon,                      -- the type constructor
464             [GenType tyvar uvar])       -- types to which it is applied
465
466 getAppTyCon ty
467   = case maybeAppTyCon ty of
468       Just stuff -> stuff
469 #ifdef DEBUG
470       Nothing    -> panic "Type.getAppTyCon" -- (ppr PprShowAll ty)
471 #endif
472 \end{code}
473
474 Applied data tycons (give back constrs)
475 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
476 \begin{code}
477 maybeAppDataTyCon
478         :: GenType (GenTyVar any) uvar
479         -> Maybe (TyCon,                -- the type constructor
480                   [GenType (GenTyVar any) uvar],        -- types to which it is applied
481                   [Id])                 -- its family of data-constructors
482 maybeAppDataTyConExpandingDicts, maybeAppSpecDataTyConExpandingDicts
483         :: Type -> Maybe (TyCon, [Type], [Id])
484
485 maybeAppDataTyCon                   ty = maybe_app_data_tycon (\x->x) ty
486 maybeAppDataTyConExpandingDicts     ty = maybe_app_data_tycon expandTy ty
487 maybeAppSpecDataTyConExpandingDicts ty = maybe_app_data_tycon expandTy ty
488
489
490 maybe_app_data_tycon expand ty
491   = let
492         expanded_ty       = expand ty
493         (app_ty, arg_tys) = splitAppTys expanded_ty
494     in
495     case (getTyCon_maybe app_ty) of
496         Just tycon |  --pprTrace "maybe_app:" (hsep [ppr PprDebug (isDataTyCon tycon), ppr PprDebug (notArrowKind (typeKind expanded_ty))]) $
497                       isDataTyCon tycon && 
498                       notArrowKind (typeKind expanded_ty)
499                         -- Must be saturated for ty to be a data type
500                    -> Just (tycon, arg_tys, tyConDataCons tycon)
501
502         other      -> Nothing
503
504 getAppDataTyCon, getAppSpecDataTyCon
505         :: GenType (GenTyVar any) uvar
506         -> (TyCon,                      -- the type constructor
507             [GenType (GenTyVar any) uvar],      -- types to which it is applied
508             [Id])                       -- its family of data-constructors
509 getAppDataTyConExpandingDicts, getAppSpecDataTyConExpandingDicts
510         :: Type -> (TyCon, [Type], [Id])
511
512 getAppDataTyCon               ty = get_app_data_tycon maybeAppDataTyCon ty
513 getAppDataTyConExpandingDicts ty = --pprTrace "getAppDataTyConEx...:" (pprType PprDebug ty) $
514                                    get_app_data_tycon maybeAppDataTyConExpandingDicts ty
515
516 -- these should work like the UniTyFuns.getUniDataSpecTyCon* things of old (ToDo)
517 getAppSpecDataTyCon               = getAppDataTyCon
518 getAppSpecDataTyConExpandingDicts = getAppDataTyConExpandingDicts
519
520 get_app_data_tycon maybe ty
521   = case maybe ty of
522       Just stuff -> stuff
523 #ifdef DEBUG
524       Nothing    -> panic "Type.getAppDataTyCon"--  (pprGenType PprShowAll ty)
525 #endif
526
527
528 maybeBoxedPrimType :: Type -> Maybe (Id, Type)
529
530 maybeBoxedPrimType ty
531   = case (maybeAppDataTyCon ty) of              -- Data type,
532       Just (tycon, tys_applied, [data_con])     -- with exactly one constructor
533         -> case (dataConArgTys data_con tys_applied) of
534              [data_con_arg_ty]                  -- Applied to exactly one type,
535                 | isPrimType data_con_arg_ty    -- which is primitive
536                 -> Just (data_con, data_con_arg_ty)
537              other_cases -> Nothing
538       other_cases -> Nothing
539 \end{code}
540
541 \begin{code}
542 splitSigmaTy :: GenType t u -> ([t], [(Class,GenType t u)], GenType t u)
543 splitSigmaTy ty =
544   (tyvars, theta, tau)
545  where
546   (tyvars,rho) = splitForAllTy ty
547   (theta,tau)  = splitRhoTy rho
548
549 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkRhoTy theta tau)
550 \end{code}
551
552
553 Finding the kind of a type
554 ~~~~~~~~~~~~~~~~~~~~~~~~~~
555 \begin{code}
556 typeKind :: GenType (GenTyVar any) u -> Kind
557
558 typeKind (TyVarTy tyvar)        = tyVarKind tyvar
559 typeKind (TyConTy tycon usage)  = tyConKind tycon
560 typeKind (SynTy _ _ ty)         = typeKind ty
561 typeKind (FunTy fun arg _)      = mkBoxedTypeKind
562 typeKind (DictTy clas arg _)    = mkBoxedTypeKind
563 typeKind (AppTy fun arg)        = resultKind (typeKind fun)
564 typeKind (ForAllTy _ _)         = mkBoxedTypeKind
565 typeKind (ForAllUsageTy _ _ _)  = mkBoxedTypeKind
566 \end{code}
567
568
569 Free variables of a type
570 ~~~~~~~~~~~~~~~~~~~~~~~~
571 \begin{code}
572 tyVarsOfType :: GenType (GenTyVar flexi) uvar -> GenTyVarSet flexi
573
574 tyVarsOfType (TyVarTy tv)               = unitTyVarSet tv
575 tyVarsOfType (TyConTy tycon usage)      = emptyTyVarSet
576 tyVarsOfType (SynTy _ tys ty)           = tyVarsOfTypes tys
577 tyVarsOfType (FunTy arg res _)          = tyVarsOfType arg `unionTyVarSets` tyVarsOfType res
578 tyVarsOfType (AppTy fun arg)            = tyVarsOfType fun `unionTyVarSets` tyVarsOfType arg
579 tyVarsOfType (DictTy clas ty _)         = tyVarsOfType ty
580 tyVarsOfType (ForAllTy tyvar ty)        = tyVarsOfType ty `minusTyVarSet` unitTyVarSet tyvar
581 tyVarsOfType (ForAllUsageTy _ _ ty)     = tyVarsOfType ty
582
583 tyVarsOfTypes :: [GenType (GenTyVar flexi) uvar] -> GenTyVarSet flexi
584 tyVarsOfTypes tys = foldr (unionTyVarSets.tyVarsOfType) emptyTyVarSet tys
585
586 -- Find the free names of a type, including the type constructors and classes it mentions
587 namesOfType :: GenType (GenTyVar flexi) uvar -> NameSet
588 namesOfType (TyVarTy tv)                = unitNameSet (getName tv)
589 namesOfType (TyConTy tycon usage)       = unitNameSet (getName tycon)
590 namesOfType (SynTy tycon tys ty)        = unitNameSet (getName tycon) `unionNameSets`
591                                           namesOfType ty
592 namesOfType (FunTy arg res _)           = namesOfType arg `unionNameSets` namesOfType res
593 namesOfType (AppTy fun arg)             = namesOfType fun `unionNameSets` namesOfType arg
594 namesOfType (DictTy clas ty _)          = unitNameSet (getName clas) `unionNameSets`
595                                           namesOfType ty
596 namesOfType (ForAllTy tyvar ty)         = namesOfType ty `minusNameSet` unitNameSet (getName tyvar)
597 namesOfType (ForAllUsageTy _ _ ty)      = panic "forall usage"
598 \end{code}
599
600
601 Instantiating a type
602 ~~~~~~~~~~~~~~~~~~~~
603 \begin{code}
604 -- applyTy :: GenType (GenTyVar flexi) uvar 
605 --      -> GenType (GenTyVar flexi) uvar 
606 --      -> GenType (GenTyVar flexi) uvar
607
608 applyTy :: Type -> Type -> Type
609
610 applyTy (SynTy _ _ fun)   arg = applyTy fun arg
611 applyTy (ForAllTy tv ty)  arg = instantiateTy [(tv,arg)] ty
612 applyTy ty@(DictTy _ _ _) arg = applyTy (expandTy ty) arg
613 applyTy other             arg = panic "applyTy"
614 \end{code}
615
616 \begin{code}
617 instantiateTy   :: [(GenTyVar flexi, GenType (GenTyVar flexi) uvar)] 
618                 -> GenType (GenTyVar flexi) uvar 
619                 -> GenType (GenTyVar flexi) uvar
620
621 instantiateTauTy :: Eq tv =>
622                    [(tv, GenType tv' u)]
623                 -> GenType tv u
624                 -> GenType tv' u
625
626 applyTypeEnvToTy :: TyVarEnv Type -> SigmaType -> SigmaType
627
628 -- instantiateTauTy works only (a) on types with no ForAlls,
629 --      and when               (b) all the type variables are being instantiated
630 -- In return it is more polymorphic than instantiateTy
631
632 instant_help ty lookup_tv deflt_tv choose_tycon
633                 if_usage if_forall bound_forall_tv_BAD deflt_forall_tv
634   = go ty
635   where
636     go (TyVarTy tv)                = case (lookup_tv tv) of
637                                        Nothing -> deflt_tv tv
638                                        Just ty -> ty
639     go ty@(TyConTy tycon usage)    = choose_tycon ty tycon usage
640     go (SynTy tycon tys ty)        = SynTy tycon (map go tys) (go ty)
641     go (FunTy arg res usage)       = FunTy (go arg) (go res) usage
642     go (AppTy fun arg)             = AppTy (go fun) (go arg)
643     go (DictTy clas ty usage)      = DictTy clas (go ty) usage
644     go (ForAllUsageTy uvar bds ty) = if_usage $
645                                      ForAllUsageTy uvar bds (go ty)
646     go (ForAllTy tv ty)            = if_forall $
647                                      (if (bound_forall_tv_BAD && maybeToBool (lookup_tv tv)) then
648                                         trace "instantiateTy: unexpected forall hit"
649                                      else
650                                         \x->x) ForAllTy (deflt_forall_tv tv) (go ty)
651
652 instantiateTy [] ty = ty
653
654 instantiateTy tenv ty
655   = instant_help ty lookup_tv deflt_tv choose_tycon
656                     if_usage if_forall bound_forall_tv_BAD deflt_forall_tv
657   where
658     lookup_tv tv = case [ty | (tv',ty) <- tenv, tv == tv'] of
659                      []   -> Nothing
660                      [ty] -> Just ty
661                      _    -> panic "instantiateTy:lookup_tv"
662
663     deflt_tv tv = TyVarTy tv
664     choose_tycon ty _ _ = ty
665     if_usage ty = ty
666     if_forall ty = ty
667     bound_forall_tv_BAD = True
668     deflt_forall_tv tv  = tv
669
670 instantiateTauTy tenv ty
671   = instant_help ty lookup_tv deflt_tv choose_tycon
672                     if_usage if_forall bound_forall_tv_BAD deflt_forall_tv
673   where
674     lookup_tv tv = case [ty | (tv',ty) <- tenv, tv == tv'] of
675                      []   -> Nothing
676                      [ty] -> Just ty
677                      _    -> panic "instantiateTauTy:lookup_tv"
678
679     deflt_tv tv = panic "instantiateTauTy"
680     choose_tycon _ tycon usage = TyConTy tycon usage
681     if_usage ty = panic "instantiateTauTy:ForAllUsageTy"
682     if_forall ty = panic "instantiateTauTy:ForAllTy"
683     bound_forall_tv_BAD = panic "instantiateTauTy:bound_forall_tv"
684     deflt_forall_tv tv  = panic "instantiateTauTy:deflt_forall_tv"
685
686
687 -- applyTypeEnv applies a type environment to a type.
688 -- It can handle shadowing; for example:
689 --      f = /\ t1 t2 -> \ d ->
690 --         letrec f' = /\ t1 -> \x -> ...(f' t1 x')...
691 --         in f' t1
692 -- Here, when we clone t1 to t1', say, we'll come across shadowing
693 -- when applying the clone environment to the type of f'.
694 --
695 -- As a sanity check, we should also check that name capture 
696 -- doesn't occur, but that means keeping track of the free variables of the
697 -- range of the TyVarEnv, which I don't do just yet.
698 --
699 -- We don't use instant_help because we need to carry in the environment
700
701 applyTypeEnvToTy tenv ty
702   = go tenv ty
703   where
704     go tenv ty@(TyVarTy tv)             = case (lookupTyVarEnv tenv tv) of
705                                              Nothing -> ty
706                                              Just ty -> ty
707     go tenv ty@(TyConTy tycon usage)    = ty
708     go tenv (SynTy tycon tys ty)        = SynTy tycon (map (go tenv) tys) (go tenv ty)
709     go tenv (FunTy arg res usage)       = FunTy (go tenv arg) (go tenv res) usage
710     go tenv (AppTy fun arg)             = AppTy (go tenv fun) (go tenv arg)
711     go tenv (DictTy clas ty usage)      = DictTy clas (go tenv ty) usage
712     go tenv (ForAllUsageTy uvar bds ty) = ForAllUsageTy uvar bds (go tenv ty)
713     go tenv (ForAllTy tv ty)            = ForAllTy tv (go tenv' ty)
714                                         where
715                                           tenv' = case lookupTyVarEnv tenv tv of
716                                                     Nothing -> tenv
717                                                     Just _  -> delFromTyVarEnv tenv tv
718 \end{code}
719
720 \begin{code}
721 instantiateUsage
722         :: Ord3 u => [(u, GenType t u')] -> GenType t u -> GenType t u'
723
724 instantiateUsage = panic "instantiateUsage: not implemented"
725 \end{code}
726
727
728 At present there are no unboxed non-primitive types, so
729 isUnboxedType is the same as isPrimType.
730
731 We're a bit cavalier about finding out whether something is
732 primitive/unboxed or not.  Rather than deal with the type
733 arguemnts we just zoom into the function part of the type.
734 That is, given (T a) we just recurse into the "T" part,
735 ignoring "a".
736
737 \begin{code}
738 isPrimType, isUnboxedType :: Type -> Bool
739
740 isPrimType (AppTy ty _)      = isPrimType ty
741 isPrimType (SynTy _ _ ty)    = isPrimType ty
742 isPrimType (TyConTy tycon _) = case maybeNewTyCon tycon of
743                                   Just (tyvars, ty) -> isPrimType ty
744                                   Nothing           -> isPrimTyCon tycon
745
746 isPrimType _                 = False
747
748 isUnboxedType = isPrimType
749 \end{code}
750
751 This is *not* right: it is a placeholder (ToDo 96/03 WDP):
752 \begin{code}
753 typePrimRep :: Type -> PrimRep
754
755 typePrimRep (SynTy _ _ ty)  = typePrimRep ty
756 typePrimRep (AppTy ty _)    = typePrimRep ty
757 typePrimRep (TyConTy tc _)  
758   | isPrimTyCon tc          = case (assocMaybe tc_primrep_list (uniqueOf tc)) of
759                                    Just xx -> xx
760                                    Nothing -> panic "Type.typePrimRep" -- pprPanic "typePrimRep:" (pprTyCon PprDebug tc)
761
762   | otherwise               = case maybeNewTyCon tc of
763                                   Just (tyvars, ty) | isPrimType ty -> typePrimRep ty
764                                   _ -> PtrRep   -- Default
765
766 typePrimRep _               = PtrRep -- the "default"
767
768 tc_primrep_list
769   = [(addrPrimTyConKey,             AddrRep)
770     ,(arrayPrimTyConKey,            ArrayRep)
771     ,(byteArrayPrimTyConKey,        ByteArrayRep)
772     ,(charPrimTyConKey,             CharRep)
773     ,(doublePrimTyConKey,           DoubleRep)
774     ,(floatPrimTyConKey,            FloatRep)
775     ,(foreignObjPrimTyConKey,       ForeignObjRep)
776     ,(intPrimTyConKey,              IntRep)
777     ,(mutableArrayPrimTyConKey,     ArrayRep)
778     ,(mutableByteArrayPrimTyConKey, ByteArrayRep)
779     ,(stablePtrPrimTyConKey,        StablePtrRep)
780     ,(statePrimTyConKey,            VoidRep)
781     ,(synchVarPrimTyConKey,         PtrRep)
782     ,(voidTyConKey,                 PtrRep)     -- Not VoidRep!  That's just for Void#
783                                                 -- The type Void is represented by a pointer to
784                                                 -- a bottom closure.
785     ,(wordPrimTyConKey,             WordRep)
786     ]
787 \end{code}
788
789 %************************************************************************
790 %*                                                                      *
791 \subsection{Matching on types}
792 %*                                                                      *
793 %************************************************************************
794
795 Matching is a {\em unidirectional} process, matching a type against a
796 template (which is just a type with type variables in it).  The
797 matcher assumes that there are no repeated type variables in the
798 template, so that it simply returns a mapping of type variables to
799 types.  It also fails on nested foralls.
800
801 @matchTys@ matches corresponding elements of a list of templates and
802 types.
803
804 \begin{code}
805 matchTy :: GenType t1 u1                -- Template
806         -> GenType t2 u2                -- Proposed instance of template
807         -> Maybe [(t1,GenType t2 u2)]   -- Matching substitution
808                                         
809
810 matchTys :: [GenType t1 u1]             -- Templates
811          -> [GenType t2 u2]             -- Proposed instance of template
812          -> Maybe ([(t1,GenType t2 u2)],-- Matching substitution
813                    [GenType t2 u2])     -- Left over instance types
814
815 matchTy  ty1  ty2  = match  ty1 ty2 (\s -> Just s) []
816 matchTys tys1 tys2 = go [] tys1 tys2
817                    where
818                      go s []        tys2        = Just (s,tys2)
819                      go s (ty1:tys1) []         = trace "matchTys" Nothing
820                      go s (ty1:tys1) (ty2:tys2) = match ty1 ty2 (\s' -> go s' tys1 tys2) s
821 \end{code}
822
823 @match@ is the main function.
824
825 \begin{code}
826 match :: GenType t1 u1 -> GenType t2 u2                 -- Current match pair
827       -> ([(t1, GenType t2 u2)] -> Maybe result)        -- Continuation
828       -> [(t1, GenType t2 u2)]                          -- Current substitution
829       -> Maybe result
830
831 match (TyVarTy v)          ty                   k = \s -> k ((v,ty) : s)
832 match (FunTy fun1 arg1 _)  (FunTy fun2 arg2 _)  k = match fun1 fun2 (match arg1 arg2 k)
833 match (AppTy fun1 arg1)    (AppTy fun2 arg2)    k = match fun1 fun2 (match arg1 arg2 k)
834 match (TyConTy con1 _)     (TyConTy con2 _)     k | con1  == con2  = k
835 match (DictTy clas1 ty1 _) (DictTy clas2 ty2 _) k | clas1 == clas2 = match ty1 ty2 k
836 match (SynTy _ _ ty1)      ty2                  k = match ty1 ty2 k
837 match ty1                      (SynTy _ _ ty2)  k = match ty1 ty2 k
838
839         -- With type synonyms, we have to be careful for the exact
840         -- same reasons as in the unifier.  Please see the
841         -- considerable commentary there before changing anything
842         -- here! (WDP 95/05)
843
844 -- Catch-all fails
845 match _ _ _ = \s -> Nothing
846 \end{code}
847
848 %************************************************************************
849 %*                                                                      *
850 \subsection{Equality on types}
851 %*                                                                      *
852 %************************************************************************
853
854 The functions eqSimpleTy and eqSimpleTheta are polymorphic in the types t
855 and u, but ONLY WORK FOR SIMPLE TYPES (ie. they panic if they see
856 dictionaries or polymorphic types).  The function eqTy has a more
857 specific type, but does the `right thing' for all types.
858
859 \begin{code}
860 eqSimpleTheta :: (Eq t,Eq u) =>
861     [(Class,GenType t u)] -> [(Class,GenType t u)] -> Bool
862
863 eqSimpleTheta [] [] = True
864 eqSimpleTheta ((c1,t1):th1) ((c2,t2):th2) =
865   c1==c2 && t1 `eqSimpleTy` t2 && th1 `eqSimpleTheta` th2
866 eqSimpleTheta other1 other2 = False
867 \end{code}
868
869 \begin{code}
870 eqSimpleTy :: (Eq t,Eq u) => GenType t u -> GenType t u -> Bool
871
872 (TyVarTy tv1) `eqSimpleTy` (TyVarTy tv2) =
873   tv1 == tv2
874 (AppTy f1 a1)  `eqSimpleTy` (AppTy f2 a2) =
875   f1 `eqSimpleTy` f2 && a1 `eqSimpleTy` a2
876 (TyConTy tc1 u1) `eqSimpleTy` (TyConTy tc2 u2) =
877   tc1 == tc2 --ToDo: later: && u1 == u2
878
879 (FunTy f1 a1 u1) `eqSimpleTy` (FunTy f2 a2 u2) =
880   f1 `eqSimpleTy` f2 && a1 `eqSimpleTy` a2 && u1 == u2
881 (FunTy f1 a1 u1) `eqSimpleTy` t2 =
882   -- Expand t1 just in case t2 matches that version
883   (AppTy (AppTy (TyConTy mkFunTyCon u1) f1) a1) `eqSimpleTy` t2
884 t1 `eqSimpleTy` (FunTy f2 a2 u2) =
885   -- Expand t2 just in case t1 matches that version
886   t1 `eqSimpleTy` (AppTy (AppTy (TyConTy mkFunTyCon u2) f2) a2)
887
888 (SynTy tc1 ts1 t1) `eqSimpleTy` (SynTy tc2 ts2 t2) =
889   (tc1 == tc2 && and (zipWith eqSimpleTy ts1 ts2) && length ts1 == length ts2)
890   || t1 `eqSimpleTy` t2
891 (SynTy _ _ t1) `eqSimpleTy` t2 =
892   t1 `eqSimpleTy` t2  -- Expand the abbrevation and try again
893 t1 `eqSimpleTy` (SynTy _ _ t2) =
894   t1 `eqSimpleTy` t2  -- Expand the abbrevation and try again
895
896 (DictTy _ _ _) `eqSimpleTy` _ = panic "eqSimpleTy: got DictTy"
897 _ `eqSimpleTy` (DictTy _ _ _) = panic "eqSimpleTy: got DictTy"
898
899 (ForAllTy _ _) `eqSimpleTy` _ = panic "eqSimpleTy: got ForAllTy"
900 _ `eqSimpleTy` (ForAllTy _ _) = panic "eqSimpleTy: got ForAllTy"
901
902 (ForAllUsageTy _ _ _) `eqSimpleTy` _ = panic "eqSimpleTy: got ForAllUsageTy"
903 _ `eqSimpleTy` (ForAllUsageTy _ _ _) = panic "eqSimpleTy: got ForAllUsageTy"
904
905 _ `eqSimpleTy` _ = False
906 \end{code}
907
908 Types are ordered so we can sort on types in the renamer etc.  DNT: Since
909 this class is also used in CoreLint and other such places, we DO expand out
910 Fun/Syn/Dict types (if necessary).
911
912 \begin{code}
913 eqTy :: Type -> Type -> Bool
914
915 eqTy t1 t2 =
916   eq nullTyVarEnv nullUVarEnv t1 t2
917  where
918   eq tve uve (TyVarTy tv1) (TyVarTy tv2) =
919     tv1 == tv2 ||
920     case (lookupTyVarEnv tve tv1) of
921       Just tv -> tv == tv2
922       Nothing -> False
923   eq tve uve (AppTy f1 a1) (AppTy f2 a2) =
924     eq tve uve f1 f2 && eq tve uve a1 a2
925   eq tve uve (TyConTy tc1 u1) (TyConTy tc2 u2) =
926     tc1 == tc2 -- ToDo: LATER: && eqUsage uve u1 u2
927
928   eq tve uve (FunTy f1 a1 u1) (FunTy f2 a2 u2) =
929     eq tve uve f1 f2 && eq tve uve a1 a2 && eqUsage uve u1 u2
930   eq tve uve (FunTy f1 a1 u1) t2 =
931     -- Expand t1 just in case t2 matches that version
932     eq tve uve (AppTy (AppTy (TyConTy mkFunTyCon u1) f1) a1) t2
933   eq tve uve t1 (FunTy f2 a2 u2) =
934     -- Expand t2 just in case t1 matches that version
935     eq tve uve t1 (AppTy (AppTy (TyConTy mkFunTyCon u2) f2) a2)
936
937   eq tve uve (DictTy c1 t1 u1) (DictTy c2 t2 u2) 
938     | c1 == c2 
939     = eq tve uve t1 t2 && eqUsage uve u1 u2
940         -- NB we use a guard for c1==c2 so that if they aren't equal we
941         -- fall through into expanding the type.  Why?  Because brain-dead
942         -- people might write
943         --      class Foo a => Baz a where {}
944         -- and that means that a Foo dictionary and a Baz dictionary are identical
945         -- Sigh.  Let's hope we don't spend too much time in here!
946
947   eq tve uve t1@(DictTy _ _ _) t2 =
948     eq tve uve (expandTy t1) t2  -- Expand the dictionary and try again
949   eq tve uve t1 t2@(DictTy _ _ _) =
950     eq tve uve t1 (expandTy t2)  -- Expand the dictionary and try again
951
952   eq tve uve (SynTy tc1 ts1 t1) (SynTy tc2 ts2 t2) =
953     (tc1 == tc2 && and (zipWith (eq tve uve) ts1 ts2) && length ts1 == length ts2)
954     || eq tve uve t1 t2
955   eq tve uve (SynTy _ _ t1) t2 =
956     eq tve uve t1 t2  -- Expand the abbrevation and try again
957   eq tve uve t1 (SynTy _ _ t2) =
958     eq tve uve t1 t2  -- Expand the abbrevation and try again
959
960   eq tve uve (ForAllTy tv1 t1) (ForAllTy tv2 t2) =
961     eq (addOneToTyVarEnv tve tv1 tv2) uve t1 t2
962   eq tve uve (ForAllUsageTy u1 b1 t1) (ForAllUsageTy u2 b2 t2) =
963     eqBounds uve b1 b2 && eq tve (addOneToUVarEnv uve u1 u2) t1 t2
964
965   eq _ _ _ _ = False
966
967   eqBounds uve [] [] = True
968   eqBounds uve (u1:b1) (u2:b2) = eqUVar uve u1 u2 && eqBounds uve b1 b2
969   eqBounds uve _ _ = False
970 \end{code}
971
972 \begin{code}
973 showTypeCategory :: Type -> Char
974   {-
975         {C,I,F,D}   char, int, float, double
976         T           tuple
977         S           other single-constructor type
978         {c,i,f,d}   unboxed ditto
979         t           *unpacked* tuple
980         s           *unpacked" single-cons...
981
982         v           void#
983         a           primitive array
984
985         E           enumeration type
986         +           dictionary, unless it's a ...
987         L           List
988         >           function
989         M           other (multi-constructor) data-con type
990         .           other type
991         -           reserved for others to mark as "uninteresting"
992     -}
993 showTypeCategory ty
994   = if isDictTy ty
995     then '+'
996     else
997       case getTyCon_maybe ty of
998         Nothing -> if maybeToBool (getFunTy_maybe ty)
999                    then '>'
1000                    else '.'
1001
1002         Just tycon ->
1003           let utc = uniqueOf tycon in
1004           if      utc == charDataConKey    then 'C'
1005           else if utc == intDataConKey     then 'I'
1006           else if utc == floatDataConKey   then 'F'
1007           else if utc == doubleDataConKey  then 'D'
1008           else if utc == integerDataConKey then 'J'
1009           else if utc == charPrimTyConKey  then 'c'
1010           else if (utc == intPrimTyConKey || utc == wordPrimTyConKey
1011                 || utc == addrPrimTyConKey)                then 'i'
1012           else if utc  == floatPrimTyConKey                then 'f'
1013           else if utc  == doublePrimTyConKey               then 'd'
1014           else if isPrimTyCon tycon {- array, we hope -}   then 'A'
1015           else if isEnumerationTyCon tycon                 then 'E'
1016           else if isTupleTyCon tycon                       then 'T'
1017           else if maybeToBool (maybeTyConSingleCon tycon)  then 'S'
1018           else if utc == listTyConKey                      then 'L'
1019           else 'M' -- oh, well...
1020 \end{code}