Small fixes to the generics branch to get rid of warnings,
[ghc-hetmet.git] / compiler / types / Type.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 %
5
6 Type - public interface
7
8 \begin{code}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 -- for details
14
15 -- | Main functions for manipulating types and type-related things
16 module Type (
17         -- Note some of this is just re-exports from TyCon..
18
19         -- * Main data types representing Types
20         -- $type_classification
21         
22         -- $representation_types
23         TyThing(..), Type, PredType(..), ThetaType,
24
25         -- ** Constructing and deconstructing types
26         mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe,
27
28         mkAppTy, mkAppTys, splitAppTy, splitAppTys, 
29         splitAppTy_maybe, repSplitAppTy_maybe,
30
31         mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, 
32         splitFunTys, splitFunTysN,
33         funResultTy, funArgTy, zipFunTys, 
34
35         mkTyConApp, mkTyConTy, 
36         tyConAppTyCon, tyConAppArgs, 
37         splitTyConApp_maybe, splitTyConApp, 
38
39         mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, 
40         applyTy, applyTys, applyTysD, isForAllTy, dropForAlls,
41         
42         -- (Newtypes)
43         newTyConInstRhs, carefullySplitNewType_maybe,
44         
45         -- (Type families)
46         tyFamInsts, predFamInsts,
47
48         -- (Source types)
49         mkPredTy, mkPredTys, mkFamilyTyConApp, isEqPred, coVarPred,
50
51         -- ** Common type constructors
52         funTyCon,
53
54         -- ** Predicates on types
55         isTyVarTy, isFunTy, isDictTy,
56
57         -- (Lifting and boxity)
58         isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
59         isPrimitiveType, isStrictType, isStrictPred, 
60
61         -- * Main data types representing Kinds
62         -- $kind_subtyping
63         Kind, SimpleKind, KindVar,
64         
65         -- ** Common Kinds and SuperKinds
66         liftedTypeKind, unliftedTypeKind, openTypeKind,
67         argTypeKind, ubxTupleKind,
68
69         tySuperKind, coSuperKind, 
70
71         -- ** Common Kind type constructors
72         liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
73         argTypeKindTyCon, ubxTupleKindTyCon,
74
75         -- * Type free variables
76         tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
77         expandTypeSynonyms, 
78         typeSize,
79
80         -- * Type comparison
81         coreEqType, coreEqType2,
82         tcEqType, tcEqTypes, tcCmpType, tcCmpTypes, 
83         tcEqPred, tcEqPredX, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
84
85         -- * Forcing evaluation of types
86         seqType, seqTypes,
87
88         -- * Other views onto Types
89         coreView, tcView, kindView,
90
91         repType, 
92
93         -- * Type representation for the code generator
94         PrimRep(..),
95
96         typePrimRep, predTypeRep,
97
98         -- * Main type substitution data types
99         TvSubstEnv,     -- Representation widely visible
100         TvSubst(..),    -- Representation visible to a few friends
101         
102         -- ** Manipulating type substitutions
103         emptyTvSubstEnv, emptyTvSubst,
104         
105         mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
106         getTvSubstEnv, setTvSubstEnv, zapTvSubstEnv, getTvInScope, 
107         extendTvInScope, extendTvInScopeList,
108         extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
109         isEmptyTvSubst, unionTvSubst,
110
111         -- ** Performing substitution on types
112         substTy, substTys, substTyWith, substTysWith, substTheta, 
113         substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
114
115         -- * Pretty-printing
116         pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
117         pprPred, pprEqPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind,
118         
119         pprSourceTyCon
120     ) where
121
122 #include "HsVersions.h"
123
124 -- We import the representation and primitive functions from TypeRep.
125 -- Many things are reexported, but not the representation!
126
127 import TypeRep
128
129 -- friends:
130 import Var
131 import VarEnv
132 import VarSet
133
134 import Class
135 import TyCon
136
137 -- others
138 import StaticFlags
139 import Util
140 import Outputable
141 import FastString
142
143 import Data.Maybe       ( isJust )
144
145 infixr 3 `mkFunTy`      -- Associates to the right
146 \end{code}
147
148 \begin{code}
149 -- $type_classification
150 -- #type_classification#
151 -- 
152 -- Types are one of:
153 -- 
154 -- [Unboxed]            Iff its representation is other than a pointer
155 --                      Unboxed types are also unlifted.
156 -- 
157 -- [Lifted]             Iff it has bottom as an element.
158 --                      Closures always have lifted types: i.e. any
159 --                      let-bound identifier in Core must have a lifted
160 --                      type. Operationally, a lifted object is one that
161 --                      can be entered.
162 --                      Only lifted types may be unified with a type variable.
163 -- 
164 -- [Algebraic]          Iff it is a type with one or more constructors, whether
165 --                      declared with @data@ or @newtype@.
166 --                      An algebraic type is one that can be deconstructed
167 --                      with a case expression. This is /not/ the same as 
168 --                      lifted types, because we also include unboxed
169 --                      tuples in this classification.
170 -- 
171 -- [Data]               Iff it is a type declared with @data@, or a boxed tuple.
172 -- 
173 -- [Primitive]          Iff it is a built-in type that can't be expressed in Haskell.
174 -- 
175 -- Currently, all primitive types are unlifted, but that's not necessarily
176 -- the case: for example, @Int@ could be primitive.
177 -- 
178 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
179 -- but unlifted (such as @ByteArray#@).  The only primitive types that we
180 -- classify as algebraic are the unboxed tuples.
181 -- 
182 -- Some examples of type classifications that may make this a bit clearer are:
183 -- 
184 -- @
185 -- Type         primitive       boxed           lifted          algebraic
186 -- -----------------------------------------------------------------------------
187 -- Int#         Yes             No              No              No
188 -- ByteArray#   Yes             Yes             No              No
189 -- (\# a, b \#)   Yes             No              No              Yes
190 -- (  a, b  )   No              Yes             Yes             Yes
191 -- [a]          No              Yes             Yes             Yes
192 -- @
193
194 -- $representation_types
195 -- A /source type/ is a type that is a separate type as far as the type checker is
196 -- concerned, but which has a more low-level representation as far as Core-to-Core
197 -- passes and the rest of the back end is concerned. Notably, 'PredTy's are removed
198 -- from the representation type while they do exist in the source types.
199 --
200 -- You don't normally have to worry about this, as the utility functions in
201 -- this module will automatically convert a source into a representation type
202 -- if they are spotted, to the best of it's abilities. If you don't want this
203 -- to happen, use the equivalent functions from the "TcType" module.
204 \end{code}
205
206 %************************************************************************
207 %*                                                                      *
208                 Type representation
209 %*                                                                      *
210 %************************************************************************
211
212 \begin{code}
213 {-# INLINE coreView #-}
214 coreView :: Type -> Maybe Type
215 -- ^ In Core, we \"look through\" non-recursive newtypes and 'PredTypes': this
216 -- function tries to obtain a different view of the supplied type given this
217 --
218 -- Strips off the /top layer only/ of a type to give 
219 -- its underlying representation type. 
220 -- Returns Nothing if there is nothing to look through.
221 --
222 -- In the case of @newtype@s, it returns one of:
223 --
224 -- 1) A vanilla 'TyConApp' (recursive newtype, or non-saturated)
225 -- 
226 -- 2) The newtype representation (otherwise), meaning the
227 --    type written in the RHS of the newtype declaration,
228 --    which may itself be a newtype
229 --
230 -- For example, with:
231 --
232 -- > newtype R = MkR S
233 -- > newtype S = MkS T
234 -- > newtype T = MkT (T -> T)
235 --
236 -- 'expandNewTcApp' on:
237 --
238 --  * @R@ gives @Just S@
239 --  * @S@ gives @Just T@
240 --  * @T@ gives @Nothing@ (no expansion)
241
242 -- By being non-recursive and inlined, this case analysis gets efficiently
243 -- joined onto the case analysis that the caller is already doing
244 coreView (PredTy p)
245   | isEqPred p             = Nothing
246   | otherwise              = Just (predTypeRep p)
247 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys 
248                            = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
249                                 -- Its important to use mkAppTys, rather than (foldl AppTy),
250                                 -- because the function part might well return a 
251                                 -- partially-applied type constructor; indeed, usually will!
252 coreView _                 = Nothing
253
254
255
256 -----------------------------------------------
257 {-# INLINE tcView #-}
258 tcView :: Type -> Maybe Type
259 -- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
260 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys 
261                          = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
262 tcView _                 = Nothing
263
264 -----------------------------------------------
265 expandTypeSynonyms :: Type -> Type
266 -- ^ Expand out all type synonyms.  Actually, it'd suffice to expand out
267 -- just the ones that discard type variables (e.g.  type Funny a = Int)
268 -- But we don't know which those are currently, so we just expand all.
269 expandTypeSynonyms ty 
270   = go ty
271   where
272     go (TyConApp tc tys)
273       | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys 
274       = go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
275       | otherwise
276       = TyConApp tc (map go tys)
277     go (TyVarTy tv)    = TyVarTy tv
278     go (AppTy t1 t2)   = AppTy (go t1) (go t2)
279     go (FunTy t1 t2)   = FunTy (go t1) (go t2)
280     go (ForAllTy tv t) = ForAllTy tv (go t)
281     go (PredTy p)      = PredTy (go_pred p)
282
283     go_pred (ClassP c ts)  = ClassP c (map go ts)
284     go_pred (IParam ip t)  = IParam ip (go t)
285     go_pred (EqPred t1 t2) = EqPred (go t1) (go t2)
286
287 -----------------------------------------------
288 {-# INLINE kindView #-}
289 kindView :: Kind -> Maybe Kind
290 -- ^ Similar to 'coreView' or 'tcView', but works on 'Kind's
291
292 -- For the moment, we don't even handle synonyms in kinds
293 kindView _            = Nothing
294 \end{code}
295
296
297 %************************************************************************
298 %*                                                                      *
299 \subsection{Constructor-specific functions}
300 %*                                                                      *
301 %************************************************************************
302
303
304 ---------------------------------------------------------------------
305                                 TyVarTy
306                                 ~~~~~~~
307 \begin{code}
308 mkTyVarTy  :: TyVar   -> Type
309 mkTyVarTy  = TyVarTy
310
311 mkTyVarTys :: [TyVar] -> [Type]
312 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
313
314 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
315 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
316 getTyVar :: String -> Type -> TyVar
317 getTyVar msg ty = case getTyVar_maybe ty of
318                     Just tv -> tv
319                     Nothing -> panic ("getTyVar: " ++ msg)
320
321 isTyVarTy :: Type -> Bool
322 isTyVarTy ty = isJust (getTyVar_maybe ty)
323
324 -- | Attempts to obtain the type variable underlying a 'Type'
325 getTyVar_maybe :: Type -> Maybe TyVar
326 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
327 getTyVar_maybe (TyVarTy tv)                 = Just tv  
328 getTyVar_maybe _                            = Nothing
329
330 \end{code}
331
332
333 ---------------------------------------------------------------------
334                                 AppTy
335                                 ~~~~~
336 We need to be pretty careful with AppTy to make sure we obey the 
337 invariant that a TyConApp is always visibly so.  mkAppTy maintains the
338 invariant: use it.
339
340 \begin{code}
341 -- | Applies a type to another, as in e.g. @k a@
342 mkAppTy :: Type -> Type -> Type
343 mkAppTy orig_ty1 orig_ty2
344   = mk_app orig_ty1
345   where
346     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
347     mk_app _                 = AppTy orig_ty1 orig_ty2
348         -- Note that the TyConApp could be an 
349         -- under-saturated type synonym.  GHC allows that; e.g.
350         --      type Foo k = k a -> k a
351         --      type Id x = x
352         --      foo :: Foo Id -> Foo Id
353         --
354         -- Here Id is partially applied in the type sig for Foo,
355         -- but once the type synonyms are expanded all is well
356
357 mkAppTys :: Type -> [Type] -> Type
358 mkAppTys orig_ty1 []        = orig_ty1
359         -- This check for an empty list of type arguments
360         -- avoids the needless loss of a type synonym constructor.
361         -- For example: mkAppTys Rational []
362         --   returns to (Ratio Integer), which has needlessly lost
363         --   the Rational part.
364 mkAppTys orig_ty1 orig_tys2
365   = mk_app orig_ty1
366   where
367     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
368                                 -- mkTyConApp: see notes with mkAppTy
369     mk_app _                 = foldl AppTy orig_ty1 orig_tys2
370
371 -------------
372 splitAppTy_maybe :: Type -> Maybe (Type, Type)
373 -- ^ Attempt to take a type application apart, whether it is a
374 -- function, type constructor, or plain type application. Note
375 -- that type family applications are NEVER unsaturated by this!
376 splitAppTy_maybe ty | Just ty' <- coreView ty
377                     = splitAppTy_maybe ty'
378 splitAppTy_maybe ty = repSplitAppTy_maybe ty
379
380 -------------
381 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
382 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that 
383 -- any Core view stuff is already done
384 repSplitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
385 repSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
386 repSplitAppTy_maybe (TyConApp tc tys) 
387   | isDecomposableTyCon tc || length tys > tyConArity tc 
388   = case snocView tys of       -- never create unsaturated type family apps
389       Just (tys', ty') -> Just (TyConApp tc tys', ty')
390       Nothing          -> Nothing
391 repSplitAppTy_maybe _other = Nothing
392 -------------
393 splitAppTy :: Type -> (Type, Type)
394 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
395 -- and panics if this is not possible
396 splitAppTy ty = case splitAppTy_maybe ty of
397                         Just pr -> pr
398                         Nothing -> panic "splitAppTy"
399
400 -------------
401 splitAppTys :: Type -> (Type, [Type])
402 -- ^ Recursively splits a type as far as is possible, leaving a residual
403 -- type being applied to and the type arguments applied to it. Never fails,
404 -- even if that means returning an empty list of type applications.
405 splitAppTys ty = split ty ty []
406   where
407     split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
408     split _       (AppTy ty arg)        args = split ty ty (arg:args)
409     split _       (TyConApp tc tc_args) args
410       = let -- keep type families saturated
411             n | isDecomposableTyCon tc = 0
412               | otherwise              = tyConArity tc
413             (tc_args1, tc_args2) = splitAt n tc_args
414         in
415         (TyConApp tc tc_args1, tc_args2 ++ args)
416     split _       (FunTy ty1 ty2)       args = ASSERT( null args )
417                                                (TyConApp funTyCon [], [ty1,ty2])
418     split orig_ty _                     args = (orig_ty, args)
419
420 \end{code}
421
422
423 ---------------------------------------------------------------------
424                                 FunTy
425                                 ~~~~~
426
427 \begin{code}
428 mkFunTy :: Type -> Type -> Type
429 -- ^ Creates a function type from the given argument and result type
430 mkFunTy arg@(PredTy (EqPred {})) res = ForAllTy (mkWildCoVar arg) res
431 mkFunTy arg                      res = FunTy    arg               res
432
433 mkFunTys :: [Type] -> Type -> Type
434 mkFunTys tys ty = foldr mkFunTy ty tys
435
436 isFunTy :: Type -> Bool 
437 isFunTy ty = isJust (splitFunTy_maybe ty)
438
439 splitFunTy :: Type -> (Type, Type)
440 -- ^ Attempts to extract the argument and result types from a type, and
441 -- panics if that is not possible. See also 'splitFunTy_maybe'
442 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
443 splitFunTy (FunTy arg res)   = (arg, res)
444 splitFunTy other             = pprPanic "splitFunTy" (ppr other)
445
446 splitFunTy_maybe :: Type -> Maybe (Type, Type)
447 -- ^ Attempts to extract the argument and result types from a type
448 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
449 splitFunTy_maybe (FunTy arg res)   = Just (arg, res)
450 splitFunTy_maybe _                 = Nothing
451
452 splitFunTys :: Type -> ([Type], Type)
453 splitFunTys ty = split [] ty ty
454   where
455     split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
456     split args _       (FunTy arg res)   = split (arg:args) res res
457     split args orig_ty _                 = (reverse args, orig_ty)
458
459 splitFunTysN :: Int -> Type -> ([Type], Type)
460 -- ^ Split off exactly the given number argument types, and panics if that is not possible
461 splitFunTysN 0 ty = ([], ty)
462 splitFunTysN n ty = ASSERT2( isFunTy ty, int n <+> ppr ty )
463                     case splitFunTy ty of { (arg, res) ->
464                     case splitFunTysN (n-1) res of { (args, res) ->
465                     (arg:args, res) }}
466
467 -- | Splits off argument types from the given type and associating
468 -- them with the things in the input list from left to right. The
469 -- final result type is returned, along with the resulting pairs of
470 -- objects and types, albeit with the list of pairs in reverse order.
471 -- Panics if there are not enough argument types for the input list.
472 zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
473 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
474   where
475     split acc []     nty _                 = (reverse acc, nty)
476     split acc xs     nty ty 
477           | Just ty' <- coreView ty        = split acc xs nty ty'
478     split acc (x:xs) _   (FunTy arg res)   = split ((x,arg):acc) xs res res
479     split _   _      _   _                 = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
480     
481 funResultTy :: Type -> Type
482 -- ^ Extract the function result type and panic if that is not possible
483 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
484 funResultTy (FunTy _arg res)  = res
485 funResultTy ty                = pprPanic "funResultTy" (ppr ty)
486
487 funArgTy :: Type -> Type
488 -- ^ Extract the function argument type and panic if that is not possible
489 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
490 funArgTy (FunTy arg _res)  = arg
491 funArgTy ty                = pprPanic "funArgTy" (ppr ty)
492 \end{code}
493
494 ---------------------------------------------------------------------
495                                 TyConApp
496                                 ~~~~~~~~
497
498 \begin{code}
499 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
500 -- Applies its arguments to the constructor from left to right
501 mkTyConApp :: TyCon -> [Type] -> Type
502 mkTyConApp tycon tys
503   | isFunTyCon tycon, [ty1,ty2] <- tys
504   = FunTy ty1 ty2
505
506   | otherwise
507   = TyConApp tycon tys
508
509 -- | Create the plain type constructor type which has been applied to no type arguments at all.
510 mkTyConTy :: TyCon -> Type
511 mkTyConTy tycon = mkTyConApp tycon []
512
513 -- splitTyConApp "looks through" synonyms, because they don't
514 -- mean a distinct type, but all other type-constructor applications
515 -- including functions are returned as Just ..
516
517 -- | The same as @fst . splitTyConApp@
518 tyConAppTyCon :: Type -> TyCon
519 tyConAppTyCon ty = fst (splitTyConApp ty)
520
521 -- | The same as @snd . splitTyConApp@
522 tyConAppArgs :: Type -> [Type]
523 tyConAppArgs ty = snd (splitTyConApp ty)
524
525 -- | Attempts to tease a type apart into a type constructor and the application
526 -- of a number of arguments to that constructor. Panics if that is not possible.
527 -- See also 'splitTyConApp_maybe'
528 splitTyConApp :: Type -> (TyCon, [Type])
529 splitTyConApp ty = case splitTyConApp_maybe ty of
530                         Just stuff -> stuff
531                         Nothing    -> pprPanic "splitTyConApp" (ppr ty)
532
533 -- | Attempts to tease a type apart into a type constructor and the application
534 -- of a number of arguments to that constructor
535 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
536 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
537 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
538 splitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
539 splitTyConApp_maybe _                 = Nothing
540
541 newTyConInstRhs :: TyCon -> [Type] -> Type
542 -- ^ Unwrap one 'layer' of newtype on a type constructor and its arguments, using an 
543 -- eta-reduced version of the @newtype@ if possible
544 newTyConInstRhs tycon tys 
545     = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
546       mkAppTys (substTyWith tvs tys1 ty) tys2
547   where
548     (tvs, ty)    = newTyConEtadRhs tycon
549     (tys1, tys2) = splitAtList tvs tys
550 \end{code}
551
552
553 ---------------------------------------------------------------------
554                                 SynTy
555                                 ~~~~~
556
557 Notes on type synonyms
558 ~~~~~~~~~~~~~~~~~~~~~~
559 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
560 to return type synonyms whereever possible. Thus
561
562         type Foo a = a -> a
563
564 we want 
565         splitFunTys (a -> Foo a) = ([a], Foo a)
566 not                                ([a], a -> a)
567
568 The reason is that we then get better (shorter) type signatures in 
569 interfaces.  Notably this plays a role in tcTySigs in TcBinds.lhs.
570
571
572 Note [Expanding newtypes]
573 ~~~~~~~~~~~~~~~~~~~~~~~~~
574 When expanding a type to expose a data-type constructor, we need to be
575 careful about newtypes, lest we fall into an infinite loop. Here are
576 the key examples:
577
578   newtype Id  x = MkId x
579   newtype Fix f = MkFix (f (Fix f))
580   newtype T     = MkT (T -> T) 
581   
582   Type           Expansion
583  --------------------------
584   T              T -> T
585   Fix Maybe      Maybe (Fix Maybe)
586   Id (Id Int)    Int
587   Fix Id         NO NO NO
588
589 Notice that we can expand T, even though it's recursive.
590 And we can expand Id (Id Int), even though the Id shows up
591 twice at the outer level.  
592
593 So, when expanding, we keep track of when we've seen a recursive
594 newtype at outermost level; and bale out if we see it again.
595
596
597                 Representation types
598                 ~~~~~~~~~~~~~~~~~~~~
599
600 \begin{code}
601 -- | Looks through:
602 --
603 --      1. For-alls
604 --      2. Synonyms
605 --      3. Predicates
606 --      4. All newtypes, including recursive ones, but not newtype families
607 --
608 -- It's useful in the back end of the compiler.
609 repType :: Type -> Type
610 -- Only applied to types of kind *; hence tycons are saturated
611 repType ty
612   = go [] ty
613   where
614     go :: [TyCon] -> Type -> Type
615     go rec_nts ty | Just ty' <- coreView ty     -- Expand synonyms
616         = go rec_nts ty'        
617
618     go rec_nts (ForAllTy _ ty)                  -- Look through foralls
619         = go rec_nts ty
620
621     go rec_nts (TyConApp tc tys)                -- Expand newtypes
622       | Just (rec_nts', ty') <- carefullySplitNewType_maybe rec_nts tc tys
623       = go rec_nts' ty'
624
625     go _ ty = ty
626
627
628 carefullySplitNewType_maybe :: [TyCon] -> TyCon -> [Type] -> Maybe ([TyCon],Type)
629 -- Return the representation of a newtype, unless 
630 -- we've seen it already: see Note [Expanding newtypes]
631 carefullySplitNewType_maybe rec_nts tc tys
632   | isNewTyCon tc
633   , not (tc `elem` rec_nts)  = Just (rec_nts', newTyConInstRhs tc tys)
634   | otherwise                = Nothing
635   where
636     rec_nts' | isRecursiveTyCon tc = tc:rec_nts
637              | otherwise           = rec_nts
638
639
640 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
641 -- of inspecting the type directly.
642
643 -- | Discovers the primitive representation of a more abstract 'Type'
644 typePrimRep :: Type -> PrimRep
645 typePrimRep ty = case repType ty of
646                    TyConApp tc _ -> tyConPrimRep tc
647                    FunTy _ _     -> PtrRep
648                    AppTy _ _     -> PtrRep      -- See note below
649                    TyVarTy _     -> PtrRep
650                    _             -> pprPanic "typePrimRep" (ppr ty)
651         -- Types of the form 'f a' must be of kind *, not *#, so
652         -- we are guaranteed that they are represented by pointers.
653         -- The reason is that f must have kind *->*, not *->*#, because
654         -- (we claim) there is no way to constrain f's kind any other
655         -- way.
656 \end{code}
657
658
659 ---------------------------------------------------------------------
660                                 ForAllTy
661                                 ~~~~~~~~
662
663 \begin{code}
664 mkForAllTy :: TyVar -> Type -> Type
665 mkForAllTy tyvar ty
666   = ForAllTy tyvar ty
667
668 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
669 mkForAllTys :: [TyVar] -> Type -> Type
670 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
671
672 isForAllTy :: Type -> Bool
673 isForAllTy (ForAllTy _ _) = True
674 isForAllTy _              = False
675
676 -- | Attempts to take a forall type apart, returning the bound type variable
677 -- and the remainder of the type
678 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
679 splitForAllTy_maybe ty = splitFAT_m ty
680   where
681     splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
682     splitFAT_m (ForAllTy tyvar ty)          = Just(tyvar, ty)
683     splitFAT_m _                            = Nothing
684
685 -- | Attempts to take a forall type apart, returning all the immediate such bound
686 -- type variables and the remainder of the type. Always suceeds, even if that means
687 -- returning an empty list of 'TyVar's
688 splitForAllTys :: Type -> ([TyVar], Type)
689 splitForAllTys ty = split ty ty []
690    where
691      split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
692      split _       (ForAllTy tv ty)  tvs = split ty ty (tv:tvs)
693      split orig_ty _                 tvs = (reverse tvs, orig_ty)
694
695 -- | Equivalent to @snd . splitForAllTys@
696 dropForAlls :: Type -> Type
697 dropForAlls ty = snd (splitForAllTys ty)
698 \end{code}
699
700 -- (mkPiType now in CoreUtils)
701
702 applyTy, applyTys
703 ~~~~~~~~~~~~~~~~~
704
705 \begin{code}
706 -- | Instantiate a forall type with one or more type arguments.
707 -- Used when we have a polymorphic function applied to type args:
708 --
709 -- > f t1 t2
710 --
711 -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
712 -- Panics if no application is possible.
713 applyTy :: Type -> Type -> Type
714 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
715 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
716 applyTy _                _   = panic "applyTy"
717
718 applyTys :: Type -> [Type] -> Type
719 -- ^ This function is interesting because:
720 --
721 --      1. The function may have more for-alls than there are args
722 --
723 --      2. Less obviously, it may have fewer for-alls
724 --
725 -- For case 2. think of:
726 --
727 -- > applyTys (forall a.a) [forall b.b, Int]
728 --
729 -- This really can happen, via dressing up polymorphic types with newtype
730 -- clothing.  Here's an example:
731 --
732 -- > newtype R = R (forall a. a->a)
733 -- > foo = case undefined :: R of
734 -- >            R f -> f ()
735
736 applyTys ty args = applyTysD empty ty args
737
738 applyTysD :: SDoc -> Type -> [Type] -> Type     -- Debug version
739 applyTysD _   orig_fun_ty []      = orig_fun_ty
740 applyTysD doc orig_fun_ty arg_tys 
741   | n_tvs == n_args     -- The vastly common case
742   = substTyWith tvs arg_tys rho_ty
743   | n_tvs > n_args      -- Too many for-alls
744   = substTyWith (take n_args tvs) arg_tys 
745                 (mkForAllTys (drop n_args tvs) rho_ty)
746   | otherwise           -- Too many type args
747   = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty )        -- Zero case gives infnite loop!
748     applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty)
749                   (drop n_tvs arg_tys)
750   where
751     (tvs, rho_ty) = splitForAllTys orig_fun_ty 
752     n_tvs = length tvs
753     n_args = length arg_tys     
754 \end{code}
755
756
757 %************************************************************************
758 %*                                                                      *
759 \subsection{Source types}
760 %*                                                                      *
761 %************************************************************************
762
763 Source types are always lifted.
764
765 The key function is predTypeRep which gives the representation of a source type:
766
767 \begin{code}
768 mkPredTy :: PredType -> Type
769 mkPredTy pred = PredTy pred
770
771 mkPredTys :: ThetaType -> [Type]
772 mkPredTys preds = map PredTy preds
773
774 isEqPred :: PredType -> Bool
775 isEqPred (EqPred _ _) = True
776 isEqPred _            = False
777
778 predTypeRep :: PredType -> Type
779 -- ^ Convert a 'PredType' to its representation type. However, it unwraps 
780 -- only the outermost level; for example, the result might be a newtype application
781 predTypeRep (IParam _ ty)     = ty
782 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
783         -- Result might be a newtype application, but the consumer will
784         -- look through that too if necessary
785 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
786
787 mkFamilyTyConApp :: TyCon -> [Type] -> Type
788 -- ^ Given a family instance TyCon and its arg types, return the
789 -- corresponding family type.  E.g:
790 --
791 -- > data family T a
792 -- > data instance T (Maybe b) = MkT b
793 --
794 -- Where the instance tycon is :RTL, so:
795 --
796 -- > mkFamilyTyConApp :RTL Int  =  T (Maybe Int)
797 mkFamilyTyConApp tc tys
798   | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
799   , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
800   = mkTyConApp fam_tc (substTys fam_subst fam_tys)
801   | otherwise
802   = mkTyConApp tc tys
803
804 -- | Pretty prints a 'TyCon', using the family instance in case of a
805 -- representation tycon.  For example:
806 --
807 -- > data T [a] = ...
808 --
809 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
810 pprSourceTyCon :: TyCon -> SDoc
811 pprSourceTyCon tycon 
812   | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
813   = ppr $ fam_tc `TyConApp` tys        -- can't be FunTyCon
814   | otherwise
815   = ppr tycon
816
817 isDictTy :: Type -> Bool
818 isDictTy ty = case splitTyConApp_maybe ty of
819                 Just (tc, _) -> isClassTyCon tc
820                 Nothing      -> False
821 \end{code}
822
823
824 %************************************************************************
825 %*                                                                      *
826              The free variables of a type
827 %*                                                                      *
828 %************************************************************************
829
830 \begin{code}
831 tyVarsOfType :: Type -> TyVarSet
832 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
833 tyVarsOfType (TyVarTy tv)     = unitVarSet tv
834 tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
835 tyVarsOfType (PredTy sty)     = tyVarsOfPred sty
836 tyVarsOfType (FunTy arg res)  = tyVarsOfType arg `unionVarSet` tyVarsOfType res
837 tyVarsOfType (AppTy fun arg)  = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
838 tyVarsOfType (ForAllTy tv ty) -- The kind of a coercion binder 
839                               -- can mention type variables!
840   | isTyVar tv                = inner_tvs `delVarSet` tv
841   | otherwise  {- Coercion -} = -- ASSERT( not (tv `elemVarSet` inner_tvs) )
842                                 inner_tvs `unionVarSet` tyVarsOfType (tyVarKind tv)
843   where
844     inner_tvs = tyVarsOfType ty
845
846 tyVarsOfTypes :: [Type] -> TyVarSet
847 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
848
849 tyVarsOfPred :: PredType -> TyVarSet
850 tyVarsOfPred (IParam _ ty)    = tyVarsOfType ty
851 tyVarsOfPred (ClassP _ tys)   = tyVarsOfTypes tys
852 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
853
854 tyVarsOfTheta :: ThetaType -> TyVarSet
855 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
856 \end{code}
857
858
859 %************************************************************************
860 %*                                                                      *
861                    Size                                                                 
862 %*                                                                      *
863 %************************************************************************
864
865 \begin{code}
866 typeSize :: Type -> Int
867 typeSize (TyVarTy _)     = 1
868 typeSize (AppTy t1 t2)   = typeSize t1 + typeSize t2
869 typeSize (FunTy t1 t2)   = typeSize t1 + typeSize t2
870 typeSize (PredTy p)      = predSize p
871 typeSize (ForAllTy _ t)  = 1 + typeSize t
872 typeSize (TyConApp _ ts) = 1 + sum (map typeSize ts)
873
874 predSize :: PredType -> Int
875 predSize (IParam _ t)   = 1 + typeSize t
876 predSize (ClassP _ ts)  = 1 + sum (map typeSize ts)
877 predSize (EqPred t1 t2) = typeSize t1 + typeSize t2
878 \end{code}
879
880
881 %************************************************************************
882 %*                                                                      *
883 \subsection{Type families}
884 %*                                                                      *
885 %************************************************************************
886
887 \begin{code}
888 -- | Finds type family instances occuring in a type after expanding synonyms.
889 tyFamInsts :: Type -> [(TyCon, [Type])]
890 tyFamInsts ty 
891   | Just exp_ty <- tcView ty    = tyFamInsts exp_ty
892 tyFamInsts (TyVarTy _)          = []
893 tyFamInsts (TyConApp tc tys) 
894   | isSynFamilyTyCon tc           = [(tc, tys)]
895   | otherwise                   = concat (map tyFamInsts tys)
896 tyFamInsts (FunTy ty1 ty2)      = tyFamInsts ty1 ++ tyFamInsts ty2
897 tyFamInsts (AppTy ty1 ty2)      = tyFamInsts ty1 ++ tyFamInsts ty2
898 tyFamInsts (ForAllTy _ ty)      = tyFamInsts ty
899 tyFamInsts (PredTy pty)         = predFamInsts pty
900
901 -- | Finds type family instances occuring in a predicate type after expanding 
902 -- synonyms.
903 predFamInsts :: PredType -> [(TyCon, [Type])]
904 predFamInsts (ClassP _cla tys) = concat (map tyFamInsts tys)
905 predFamInsts (IParam _ ty)     = tyFamInsts ty
906 predFamInsts (EqPred ty1 ty2)  = tyFamInsts ty1 ++ tyFamInsts ty2
907 \end{code}
908
909
910 %************************************************************************
911 %*                                                                      *
912 \subsection{Liftedness}
913 %*                                                                      *
914 %************************************************************************
915
916 \begin{code}
917 -- | See "Type#type_classification" for what an unlifted type is
918 isUnLiftedType :: Type -> Bool
919         -- isUnLiftedType returns True for forall'd unlifted types:
920         --      x :: forall a. Int#
921         -- I found bindings like these were getting floated to the top level.
922         -- They are pretty bogus types, mind you.  It would be better never to
923         -- construct them
924
925 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
926 isUnLiftedType (ForAllTy _ ty)   = isUnLiftedType ty
927 isUnLiftedType (TyConApp tc _)   = isUnLiftedTyCon tc
928 isUnLiftedType _                 = False
929
930 isUnboxedTupleType :: Type -> Bool
931 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
932                            Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
933                            _                   -> False
934
935 -- | See "Type#type_classification" for what an algebraic type is.
936 -- Should only be applied to /types/, as opposed to e.g. partially
937 -- saturated type constructors
938 isAlgType :: Type -> Bool
939 isAlgType ty 
940   = case splitTyConApp_maybe ty of
941       Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
942                             isAlgTyCon tc
943       _other             -> False
944
945 -- | See "Type#type_classification" for what an algebraic type is.
946 -- Should only be applied to /types/, as opposed to e.g. partially
947 -- saturated type constructors. Closed type constructors are those
948 -- with a fixed right hand side, as opposed to e.g. associated types
949 isClosedAlgType :: Type -> Bool
950 isClosedAlgType ty
951   = case splitTyConApp_maybe ty of
952       Just (tc, ty_args) | isAlgTyCon tc && not (isFamilyTyCon tc)
953              -> ASSERT2( ty_args `lengthIs` tyConArity tc, ppr ty ) True
954       _other -> False
955 \end{code}
956
957 \begin{code}
958 -- | Computes whether an argument (or let right hand side) should
959 -- be computed strictly or lazily, based only on its type.
960 -- Works just like 'isUnLiftedType', except that it has a special case 
961 -- for dictionaries (i.e. does not work purely on representation types)
962
963 -- Since it takes account of class 'PredType's, you might think
964 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
965 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
966 isStrictType :: Type -> Bool
967 isStrictType (PredTy pred)     = isStrictPred pred
968 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
969 isStrictType (ForAllTy _ ty)   = isStrictType ty
970 isStrictType (TyConApp tc _)   = isUnLiftedTyCon tc
971 isStrictType _                 = False
972
973 -- | We may be strict in dictionary types, but only if it 
974 -- has more than one component.
975 --
976 -- (Being strict in a single-component dictionary risks
977 --  poking the dictionary component, which is wrong.)
978 isStrictPred :: PredType -> Bool
979 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
980 isStrictPred _               = False
981 \end{code}
982
983 \begin{code}
984 isPrimitiveType :: Type -> Bool
985 -- ^ Returns true of types that are opaque to Haskell.
986 -- Most of these are unlifted, but now that we interact with .NET, we
987 -- may have primtive (foreign-imported) types that are lifted
988 isPrimitiveType ty = case splitTyConApp_maybe ty of
989                         Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
990                                               isPrimTyCon tc
991                         _                  -> False
992 \end{code}
993
994
995 %************************************************************************
996 %*                                                                      *
997 \subsection{Sequencing on types}
998 %*                                                                      *
999 %************************************************************************
1000
1001 \begin{code}
1002 seqType :: Type -> ()
1003 seqType (TyVarTy tv)      = tv `seq` ()
1004 seqType (AppTy t1 t2)     = seqType t1 `seq` seqType t2
1005 seqType (FunTy t1 t2)     = seqType t1 `seq` seqType t2
1006 seqType (PredTy p)        = seqPred p
1007 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
1008 seqType (ForAllTy tv ty)  = tv `seq` seqType ty
1009
1010 seqTypes :: [Type] -> ()
1011 seqTypes []       = ()
1012 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1013
1014 seqPred :: PredType -> ()
1015 seqPred (ClassP c tys)   = c `seq` seqTypes tys
1016 seqPred (IParam n ty)    = n `seq` seqType ty
1017 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
1018 \end{code}
1019
1020
1021 %************************************************************************
1022 %*                                                                      *
1023                 Equality for Core types 
1024         (We don't use instances so that we know where it happens)
1025 %*                                                                      *
1026 %************************************************************************
1027
1028 Note that eqType works right even for partial applications of newtypes.
1029 See Note [Newtype eta] in TyCon.lhs
1030
1031 \begin{code}
1032 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1033 coreEqType :: Type -> Type -> Bool
1034 coreEqType t1 t2 = coreEqType2 rn_env t1 t2
1035   where
1036     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1037
1038 coreEqType2 :: RnEnv2 -> Type -> Type -> Bool
1039 coreEqType2 rn_env t1 t2
1040   = eq rn_env t1 t2
1041   where
1042     eq env (TyVarTy tv1)       (TyVarTy tv2)     = rnOccL env tv1 == rnOccR env tv2
1043     eq env (ForAllTy tv1 t1)   (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1044     eq env (AppTy s1 t1)       (AppTy s2 t2)     = eq env s1 s2 && eq env t1 t2
1045     eq env (FunTy s1 t1)       (FunTy s2 t2)     = eq env s1 s2 && eq env t1 t2
1046     eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
1047         | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1048                         -- The lengths should be equal because
1049                         -- the two types have the same kind
1050         -- NB: if the type constructors differ that does not 
1051         --     necessarily mean that the types aren't equal
1052         --     (synonyms, newtypes)
1053         -- Even if the type constructors are the same, but the arguments
1054         -- differ, the two types could be the same (e.g. if the arg is just
1055         -- ignored in the RHS).  In both these cases we fall through to an 
1056         -- attempt to expand one side or the other.
1057
1058         -- Now deal with newtypes, synonyms, pred-tys
1059     eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2 
1060                  | Just t2' <- coreView t2 = eq env t1 t2' 
1061
1062         -- Fall through case; not equal!
1063     eq _ _ _ = False
1064 \end{code}
1065
1066
1067 %************************************************************************
1068 %*                                                                      *
1069                 Comparision for source types 
1070         (We don't use instances so that we know where it happens)
1071 %*                                                                      *
1072 %************************************************************************
1073
1074 \begin{code}
1075 tcEqType :: Type -> Type -> Bool
1076 -- ^ Type equality on source types. Does not look through @newtypes@ or 
1077 -- 'PredType's, but it does look through type synonyms.
1078 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1079
1080 tcEqTypes :: [Type] -> [Type] -> Bool
1081 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1082
1083 tcCmpType :: Type -> Type -> Ordering
1084 -- ^ Type ordering on source types. Does not look through @newtypes@ or 
1085 -- 'PredType's, but it does look through type synonyms.
1086 tcCmpType t1 t2 = cmpType t1 t2
1087
1088 tcCmpTypes :: [Type] -> [Type] -> Ordering
1089 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1090
1091 tcEqPred :: PredType -> PredType -> Bool
1092 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1093
1094 tcEqPredX :: RnEnv2 -> PredType -> PredType -> Bool
1095 tcEqPredX env p1 p2 = isEqual $ cmpPredX env p1 p2
1096
1097 tcCmpPred :: PredType -> PredType -> Ordering
1098 tcCmpPred p1 p2 = cmpPred p1 p2
1099
1100 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1101 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1102 \end{code}
1103
1104 \begin{code}
1105 -- | Checks whether the second argument is a subterm of the first.  (We don't care
1106 -- about binders, as we are only interested in syntactic subterms.)
1107 tcPartOfType :: Type -> Type -> Bool
1108 tcPartOfType t1              t2 
1109   | tcEqType t1 t2              = True
1110 tcPartOfType t1              t2 
1111   | Just t2' <- tcView t2       = tcPartOfType t1 t2'
1112 tcPartOfType _  (TyVarTy _)     = False
1113 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1114 tcPartOfType t1 (AppTy s2 t2)   = tcPartOfType t1 s2 || tcPartOfType t1 t2
1115 tcPartOfType t1 (FunTy s2 t2)   = tcPartOfType t1 s2 || tcPartOfType t1 t2
1116 tcPartOfType t1 (PredTy p2)     = tcPartOfPred t1 p2
1117 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1118
1119 tcPartOfPred :: Type -> PredType -> Bool
1120 tcPartOfPred t1 (IParam _ t2)  = tcPartOfType t1 t2
1121 tcPartOfPred t1 (ClassP _ ts)  = any (tcPartOfType t1) ts
1122 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1123 \end{code}
1124
1125 Now here comes the real worker
1126
1127 \begin{code}
1128 cmpType :: Type -> Type -> Ordering
1129 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1130   where
1131     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1132
1133 cmpTypes :: [Type] -> [Type] -> Ordering
1134 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1135   where
1136     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1137
1138 cmpPred :: PredType -> PredType -> Ordering
1139 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1140   where
1141     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1142
1143 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering  -- Main workhorse
1144 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1145                    | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1146
1147 cmpTypeX env (TyVarTy tv1)       (TyVarTy tv2)       = rnOccL env tv1 `compare` rnOccR env tv2
1148 cmpTypeX env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1149 cmpTypeX env (AppTy s1 t1)       (AppTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1150 cmpTypeX env (FunTy s1 t1)       (FunTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1151 cmpTypeX env (PredTy p1)         (PredTy p2)         = cmpPredX env p1 p2
1152 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1153
1154     -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1155 cmpTypeX _ (AppTy _ _)    (TyVarTy _)    = GT
1156
1157 cmpTypeX _ (FunTy _ _)    (TyVarTy _)    = GT
1158 cmpTypeX _ (FunTy _ _)    (AppTy _ _)    = GT
1159
1160 cmpTypeX _ (TyConApp _ _) (TyVarTy _)    = GT
1161 cmpTypeX _ (TyConApp _ _) (AppTy _ _)    = GT
1162 cmpTypeX _ (TyConApp _ _) (FunTy _ _)    = GT
1163
1164 cmpTypeX _ (ForAllTy _ _) (TyVarTy _)    = GT
1165 cmpTypeX _ (ForAllTy _ _) (AppTy _ _)    = GT
1166 cmpTypeX _ (ForAllTy _ _) (FunTy _ _)    = GT
1167 cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
1168
1169 cmpTypeX _ (PredTy _)     _              = GT
1170
1171 cmpTypeX _ _              _              = LT
1172
1173 -------------
1174 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1175 cmpTypesX _   []        []        = EQ
1176 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1177 cmpTypesX _   []        _         = LT
1178 cmpTypesX _   _         []        = GT
1179
1180 -------------
1181 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1182 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1183         -- Compare names only for implicit parameters
1184         -- This comparison is used exclusively (I believe) 
1185         -- for the Avails finite map built in TcSimplify
1186         -- If the types differ we keep them distinct so that we see 
1187         -- a distinct pair to run improvement on 
1188 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1189 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1190
1191 -- Constructor order: IParam < ClassP < EqPred
1192 cmpPredX _   (IParam {})     _              = LT
1193 cmpPredX _   (ClassP {})    (IParam {})     = GT
1194 cmpPredX _   (ClassP {})    (EqPred {})     = LT
1195 cmpPredX _   (EqPred {})    _               = GT
1196 \end{code}
1197
1198 PredTypes are used as a FM key in TcSimplify, 
1199 so we take the easy path and make them an instance of Ord
1200
1201 \begin{code}
1202 instance Eq  PredType where { (==)    = tcEqPred }
1203 instance Ord PredType where { compare = tcCmpPred }
1204 \end{code}
1205
1206
1207 %************************************************************************
1208 %*                                                                      *
1209                 Type substitutions
1210 %*                                                                      *
1211 %************************************************************************
1212
1213 \begin{code}
1214 -- | Type substitution
1215 --
1216 -- #tvsubst_invariant#
1217 -- The following invariants must hold of a 'TvSubst':
1218 -- 
1219 -- 1. The in-scope set is needed /only/ to
1220 -- guide the generation of fresh uniques
1221 --
1222 -- 2. In particular, the /kind/ of the type variables in 
1223 -- the in-scope set is not relevant
1224 --
1225 -- 3. The substition is only applied ONCE! This is because
1226 -- in general such application will not reached a fixed point.
1227 data TvSubst            
1228   = TvSubst InScopeSet  -- The in-scope type variables
1229             TvSubstEnv  -- The substitution itself
1230         -- See Note [Apply Once]
1231         -- and Note [Extending the TvSubstEnv]
1232
1233 {- ----------------------------------------------------------
1234
1235 Note [Apply Once]
1236 ~~~~~~~~~~~~~~~~~
1237 We use TvSubsts to instantiate things, and we might instantiate
1238         forall a b. ty
1239 \with the types
1240         [a, b], or [b, a].
1241 So the substition might go [a->b, b->a].  A similar situation arises in Core
1242 when we find a beta redex like
1243         (/\ a /\ b -> e) b a
1244 Then we also end up with a substition that permutes type variables. Other
1245 variations happen to; for example [a -> (a, b)].  
1246
1247         ***************************************************
1248         *** So a TvSubst must be applied precisely once ***
1249         ***************************************************
1250
1251 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1252 we use during unifications, it must not be repeatedly applied.
1253
1254 Note [Extending the TvSubst]
1255 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1256 See #tvsubst_invariant# for the invariants that must hold.
1257
1258 This invariant allows a short-cut when the TvSubstEnv is empty:
1259 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1260 then (substTy subst ty) does nothing.
1261
1262 For example, consider:
1263         (/\a. /\b:(a~Int). ...b..) Int
1264 We substitute Int for 'a'.  The Unique of 'b' does not change, but
1265 nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
1266
1267 This invariant has several crucial consequences:
1268
1269 * In substTyVarBndr, we need extend the TvSubstEnv 
1270         - if the unique has changed
1271         - or if the kind has changed
1272
1273 * In substTyVar, we do not need to consult the in-scope set;
1274   the TvSubstEnv is enough
1275
1276 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1277   
1278
1279 -------------------------------------------------------------- -}
1280
1281 -- | A substitition of 'Type's for 'TyVar's
1282 type TvSubstEnv = TyVarEnv Type
1283         -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1284         -- invariant discussed in Note [Apply Once]), and also independently
1285         -- in the middle of matching, and unification (see Types.Unify)
1286         -- So you have to look at the context to know if it's idempotent or
1287         -- apply-once or whatever
1288
1289 emptyTvSubstEnv :: TvSubstEnv
1290 emptyTvSubstEnv = emptyVarEnv
1291
1292 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1293 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1294 -- It assumes that both are idempotent.
1295 -- Typically, @env1@ is the refinement to a base substitution @env2@
1296 composeTvSubst in_scope env1 env2
1297   = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1298         -- First apply env1 to the range of env2
1299         -- Then combine the two, making sure that env1 loses if
1300         -- both bind the same variable; that's why env1 is the
1301         --  *left* argument to plusVarEnv, because the right arg wins
1302   where
1303     subst1 = TvSubst in_scope env1
1304
1305 emptyTvSubst :: TvSubst
1306 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1307
1308 isEmptyTvSubst :: TvSubst -> Bool
1309          -- See Note [Extending the TvSubstEnv]
1310 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1311
1312 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1313 mkTvSubst = TvSubst
1314
1315 getTvSubstEnv :: TvSubst -> TvSubstEnv
1316 getTvSubstEnv (TvSubst _ env) = env
1317
1318 getTvInScope :: TvSubst -> InScopeSet
1319 getTvInScope (TvSubst in_scope _) = in_scope
1320
1321 isInScope :: Var -> TvSubst -> Bool
1322 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1323
1324 notElemTvSubst :: TyVar -> TvSubst -> Bool
1325 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1326
1327 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1328 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1329
1330 zapTvSubstEnv :: TvSubst -> TvSubst
1331 zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv
1332
1333 extendTvInScope :: TvSubst -> Var -> TvSubst
1334 extendTvInScope (TvSubst in_scope env) var = TvSubst (extendInScopeSet in_scope var) env
1335
1336 extendTvInScopeList :: TvSubst -> [Var] -> TvSubst
1337 extendTvInScopeList (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1338
1339 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1340 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1341
1342 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1343 extendTvSubstList (TvSubst in_scope env) tvs tys 
1344   = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1345
1346 unionTvSubst :: TvSubst -> TvSubst -> TvSubst
1347 -- Works when the ranges are disjoint
1348 unionTvSubst (TvSubst in_scope1 env1) (TvSubst in_scope2 env2)
1349   = ASSERT( not (env1 `intersectsVarEnv` env2) )
1350     TvSubst (in_scope1 `unionInScope` in_scope2)
1351             (env1      `plusVarEnv`   env2)
1352
1353 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1354 -- the types given; but it's just a thunk so with a bit of luck
1355 -- it'll never be evaluated
1356
1357 -- Note [Generating the in-scope set for a substitution]
1358 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1359 -- If we want to substitute [a -> ty1, b -> ty2] I used to 
1360 -- think it was enough to generate an in-scope set that includes
1361 -- fv(ty1,ty2).  But that's not enough; we really should also take the
1362 -- free vars of the type we are substituting into!  Example:
1363 --      (forall b. (a,b,x)) [a -> List b]
1364 -- Then if we use the in-scope set {b}, there is a danger we will rename
1365 -- the forall'd variable to 'x' by mistake, getting this:
1366 --      (forall x. (List b, x, x)
1367 -- Urk!  This means looking at all the calls to mkOpenTvSubst....
1368
1369
1370 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1371 -- environment, hence "open"
1372 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1373 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1374
1375 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1376 -- environment, hence "open"
1377 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1378 zipOpenTvSubst tyvars tys 
1379   | debugIsOn && (length tyvars /= length tys)
1380   = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1381   | otherwise
1382   = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1383
1384 -- | Called when doing top-level substitutions. Here we expect that the 
1385 -- free vars of the range of the substitution will be empty.
1386 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1387 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1388
1389 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1390 zipTopTvSubst tyvars tys 
1391   | debugIsOn && (length tyvars /= length tys)
1392   = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1393   | otherwise
1394   = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1395
1396 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1397 zipTyEnv tyvars tys
1398   | debugIsOn && (length tyvars /= length tys)
1399   = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1400   | otherwise
1401   = zip_ty_env tyvars tys emptyVarEnv
1402
1403 -- Later substitutions in the list over-ride earlier ones, 
1404 -- but there should be no loops
1405 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1406 zip_ty_env []       []       env = env
1407 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1408         -- There used to be a special case for when 
1409         --      ty == TyVarTy tv
1410         -- (a not-uncommon case) in which case the substitution was dropped.
1411         -- But the type-tidier changes the print-name of a type variable without
1412         -- changing the unique, and that led to a bug.   Why?  Pre-tidying, we had 
1413         -- a type {Foo t}, where Foo is a one-method class.  So Foo is really a newtype.
1414         -- And it happened that t was the type variable of the class.  Post-tiding, 
1415         -- it got turned into {Foo t2}.  The ext-core printer expanded this using
1416         -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1417         -- and so generated a rep type mentioning t not t2.  
1418         --
1419         -- Simplest fix is to nuke the "optimisation"
1420 zip_ty_env tvs      tys      env   = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1421 -- zip_ty_env _ _ env = env
1422
1423 instance Outputable TvSubst where
1424   ppr (TvSubst ins env) 
1425     = brackets $ sep[ ptext (sLit "TvSubst"),
1426                       nest 2 (ptext (sLit "In scope:") <+> ppr ins), 
1427                       nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1428 \end{code}
1429
1430 %************************************************************************
1431 %*                                                                      *
1432                 Performing type substitutions
1433 %*                                                                      *
1434 %************************************************************************
1435
1436 \begin{code}
1437 -- | Type substitution making use of an 'TvSubst' that
1438 -- is assumed to be open, see 'zipOpenTvSubst'
1439 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1440 substTyWith tvs tys = ASSERT( length tvs == length tys )
1441                       substTy (zipOpenTvSubst tvs tys)
1442
1443 -- | Type substitution making use of an 'TvSubst' that
1444 -- is assumed to be open, see 'zipOpenTvSubst'
1445 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1446 substTysWith tvs tys = ASSERT( length tvs == length tys )
1447                        substTys (zipOpenTvSubst tvs tys)
1448
1449 -- | Substitute within a 'Type'
1450 substTy :: TvSubst -> Type  -> Type
1451 substTy subst ty | isEmptyTvSubst subst = ty
1452                  | otherwise            = subst_ty subst ty
1453
1454 -- | Substitute within several 'Type's
1455 substTys :: TvSubst -> [Type] -> [Type]
1456 substTys subst tys | isEmptyTvSubst subst = tys
1457                    | otherwise            = map (subst_ty subst) tys
1458
1459 -- | Substitute within a 'ThetaType'
1460 substTheta :: TvSubst -> ThetaType -> ThetaType
1461 substTheta subst theta
1462   | isEmptyTvSubst subst = theta
1463   | otherwise            = map (substPred subst) theta
1464
1465 -- | Substitute within a 'PredType'
1466 substPred :: TvSubst -> PredType -> PredType
1467 substPred subst (IParam n ty)     = IParam n (subst_ty subst ty)
1468 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1469 substPred subst (EqPred ty1 ty2)  = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1470
1471 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1472 deShadowTy :: TyVarSet -> Type -> Type
1473 deShadowTy tvs ty 
1474   = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1475   where
1476     in_scope = mkInScopeSet tvs
1477
1478 subst_ty :: TvSubst -> Type -> Type
1479 -- subst_ty is the main workhorse for type substitution
1480 --
1481 -- Note that the in_scope set is poked only if we hit a forall
1482 -- so it may often never be fully computed 
1483 subst_ty subst ty
1484    = go ty
1485   where
1486     go (TyVarTy tv)      = substTyVar subst tv
1487     go (TyConApp tc tys) = let args = map go tys
1488                            in  args `seqList` TyConApp tc args
1489
1490     go (PredTy p)        = PredTy $! (substPred subst p)
1491
1492     go (FunTy arg res)   = (FunTy $! (go arg)) $! (go res)
1493     go (AppTy fun arg)   = mkAppTy (go fun) $! (go arg)
1494                 -- The mkAppTy smart constructor is important
1495                 -- we might be replacing (a Int), represented with App
1496                 -- by [Int], represented with TyConApp
1497     go (ForAllTy tv ty)  = case substTyVarBndr subst tv of
1498                               (subst', tv') ->
1499                                  ForAllTy tv' $! (subst_ty subst' ty)
1500
1501 substTyVar :: TvSubst -> TyVar  -> Type
1502 substTyVar subst@(TvSubst _ _) tv
1503   = case lookupTyVar subst tv of {
1504         Nothing -> TyVarTy tv;
1505         Just ty -> ty   -- See Note [Apply Once]
1506     } 
1507
1508 substTyVars :: TvSubst -> [TyVar] -> [Type]
1509 substTyVars subst tvs = map (substTyVar subst) tvs
1510
1511 lookupTyVar :: TvSubst -> TyVar  -> Maybe Type
1512         -- See Note [Extending the TvSubst]
1513 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1514
1515 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)  
1516 substTyVarBndr subst@(TvSubst in_scope env) old_var
1517   = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1518   where
1519     is_co_var = isCoVar old_var
1520
1521     new_env | no_change = delVarEnv env old_var
1522             | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1523
1524     no_change = new_var == old_var && not is_co_var
1525         -- no_change means that the new_var is identical in
1526         -- all respects to the old_var (same unique, same kind)
1527         -- See Note [Extending the TvSubst]
1528         --
1529         -- In that case we don't need to extend the substitution
1530         -- to map old to new.  But instead we must zap any 
1531         -- current substitution for the variable. For example:
1532         --      (\x.e) with id_subst = [x |-> e']
1533         -- Here we must simply zap the substitution for x
1534
1535     new_var = uniqAway in_scope subst_old_var
1536         -- The uniqAway part makes sure the new variable is not already in scope
1537
1538     subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1539                   -- It's only worth doing the substitution for coercions,
1540                   -- becuase only they can have free type variables
1541         | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1542         | otherwise = old_var
1543 \end{code}
1544
1545 ----------------------------------------------------
1546 -- Kind Stuff
1547
1548 Kinds
1549 ~~~~~
1550
1551 \begin{code}
1552 -- $kind_subtyping
1553 -- #kind_subtyping#
1554 -- There's a little subtyping at the kind level:
1555 --
1556 -- @
1557 --               ?
1558 --              \/ &#92;
1559 --             \/   &#92;
1560 --            ??   (\#)
1561 --           \/  &#92;
1562 --          \*    \#
1563 -- .
1564 -- Where:        \*    [LiftedTypeKind]   means boxed type
1565 --              \#    [UnliftedTypeKind] means unboxed type
1566 --              (\#)  [UbxTupleKind]     means unboxed tuple
1567 --              ??   [ArgTypeKind]      is the lub of {\*, \#}
1568 --              ?    [OpenTypeKind]     means any type at all
1569 -- @
1570 --
1571 -- In particular:
1572 --
1573 -- > error :: forall a:?. String -> a
1574 -- > (->)  :: ?? -> ? -> \*
1575 -- > (\\(x::t) -> ...)
1576 --
1577 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1578
1579 type KindVar = TyVar  -- invariant: KindVar will always be a 
1580                       -- TcTyVar with details MetaTv TauTv ...
1581 -- kind var constructors and functions are in TcType
1582
1583 type SimpleKind = Kind
1584 \end{code}
1585
1586 Kind inference
1587 ~~~~~~~~~~~~~~
1588 During kind inference, a kind variable unifies only with 
1589 a "simple kind", sk
1590         sk ::= * | sk1 -> sk2
1591 For example 
1592         data T a = MkT a (T Int#)
1593 fails.  We give T the kind (k -> *), and the kind variable k won't unify
1594 with # (the kind of Int#).
1595
1596 Type inference
1597 ~~~~~~~~~~~~~~
1598 When creating a fresh internal type variable, we give it a kind to express 
1599 constraints on it.  E.g. in (\x->e) we make up a fresh type variable for x, 
1600 with kind ??.  
1601
1602 During unification we only bind an internal type variable to a type
1603 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1604
1605 When unifying two internal type variables, we collect their kind constraints by
1606 finding the GLB of the two.  Since the partial order is a tree, they only
1607 have a glb if one is a sub-kind of the other.  In that case, we bind the
1608 less-informative one to the more informative one.  Neat, eh?