This BIG PATCH contains most of the work for the New Coercion Representation
[ghc-hetmet.git] / compiler / types / TypeRep.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 %
5 \section[TypeRep]{Type - friends' interface}
6
7 \begin{code}
8 -- We expose the relevant stuff from this module via the Type module
9 {-# OPTIONS_HADDOCK hide #-}
10 {-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
11 module TypeRep (
12         TyThing(..), 
13         Type(..),
14         Pred(..),                       -- to friends
15         
16         Kind, SuperKind,
17         PredType, ThetaType,      -- Synonyms
18
19         -- Functions over types
20         mkTyConApp, mkTyConTy, mkTyVarTy, mkTyVarTys,
21         isLiftedTypeKind, isCoercionKind, 
22
23         -- Pretty-printing
24         pprType, pprParendType, pprTypeApp,
25         pprTyThing, pprTyThingCategory, 
26         pprPredTy, pprEqPred, pprTheta, pprForAll, pprThetaArrowTy, pprClassPred,
27         pprKind, pprParendKind,
28         Prec(..), maybeParen, pprTcApp, pprTypeNameApp, 
29         pprPrefixApp, pprPred, pprArrowChain, pprThetaArrow,
30
31         -- Free variables
32         tyVarsOfType, tyVarsOfTypes,
33         tyVarsOfPred, tyVarsOfTheta,
34         varsOfPred, varsOfTheta,
35         predSize,
36
37         -- Substitutions
38         TvSubst(..), TvSubstEnv
39     ) where
40
41 #include "HsVersions.h"
42
43 import {-# SOURCE #-} DataCon( DataCon, dataConName )
44
45 -- friends:
46 import Var
47 import VarEnv
48 import VarSet
49 import Name
50 import BasicTypes
51 import TyCon
52 import Class
53
54 -- others
55 import PrelNames
56 import Outputable
57 import FastString
58 import Pair
59
60 -- libraries
61 import qualified Data.Data        as Data hiding ( TyCon )
62 import qualified Data.Foldable    as Data
63 import qualified Data.Traversable as Data
64 \end{code}
65
66         ----------------------
67         A note about newtypes
68         ----------------------
69
70 Consider
71         newtype N = MkN Int
72
73 Then we want N to be represented as an Int, and that's what we arrange.
74 The front end of the compiler [TcType.lhs] treats N as opaque, 
75 the back end treats it as transparent [Type.lhs].
76
77 There's a bit of a problem with recursive newtypes
78         newtype P = MkP P
79         newtype Q = MkQ (Q->Q)
80
81 Here the 'implicit expansion' we get from treating P and Q as transparent
82 would give rise to infinite types, which in turn makes eqType diverge.
83 Similarly splitForAllTys and splitFunTys can get into a loop.  
84
85 Solution: 
86
87 * Newtypes are always represented using TyConApp.
88
89 * For non-recursive newtypes, P, treat P just like a type synonym after 
90   type-checking is done; i.e. it's opaque during type checking (functions
91   from TcType) but transparent afterwards (functions from Type).  
92   "Treat P as a type synonym" means "all functions expand NewTcApps 
93   on the fly".
94
95   Applications of the data constructor P simply vanish:
96         P x = x
97   
98
99 * For recursive newtypes Q, treat the Q and its representation as 
100   distinct right through the compiler.  Applications of the data consructor
101   use a coerce:
102         Q = \(x::Q->Q). coerce Q x
103   They are rare, so who cares if they are a tiny bit less efficient.
104
105 The typechecker (TcTyDecls) identifies enough type construtors as 'recursive'
106 to cut all loops.  The other members of the loop may be marked 'non-recursive'.
107
108
109 %************************************************************************
110 %*                                                                      *
111 \subsection{The data type}
112 %*                                                                      *
113 %************************************************************************
114
115
116 \begin{code}
117 -- | The key representation of types within the compiler
118 data Type
119   = TyVarTy TyVar       -- ^ Vanilla type variable (*never* a coercion variable)
120
121   | AppTy
122         Type
123         Type            -- ^ Type application to something other than a 'TyCon'. Parameters:
124                         --
125                         --  1) Function: must /not/ be a 'TyConApp',
126                         --     must be another 'AppTy', or 'TyVarTy'
127                         --
128                         --  2) Argument type
129
130   | TyConApp
131         TyCon
132         [Type]          -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
133                         -- Invariant: saturated appliations of 'FunTyCon' must
134                         -- use 'FunTy' and saturated synonyms must use their own
135                         -- constructors. However, /unsaturated/ 'FunTyCon's
136                         -- do appear as 'TyConApp's.
137                         -- Parameters:
138                         --
139                         -- 1) Type constructor being applied to.
140                         --
141                         -- 2) Type arguments. Might not have enough type arguments
142                         --    here to saturate the constructor.
143                         --    Even type synonyms are not necessarily saturated;
144                         --    for example unsaturated type synonyms
145                         --    can appear as the right hand side of a type synonym.
146
147   | FunTy
148         Type
149         Type            -- ^ Special case of 'TyConApp': @TyConApp FunTyCon [t1, t2]@
150
151   | ForAllTy
152         TyCoVar         -- ^ Type *or* coercion variable; see Note [Equality-constrained types]
153         Type            -- ^ A polymorphic type
154
155   | PredTy
156         PredType        -- ^ The type of evidence for a type predictate.
157                         -- Note that a @PredTy (EqPred _ _)@ can appear only as the kind
158                         -- of a coercion variable; never as the argument or result of a
159                         -- 'FunTy' (unlike the 'PredType' constructors 'ClassP' or 'IParam')
160                         
161                         -- See Note [PredTy], and Note [Equality predicates]
162   deriving (Data.Data, Data.Typeable)
163
164 -- | The key type representing kinds in the compiler.
165 -- Invariant: a kind is always in one of these forms:
166 --
167 -- > FunTy k1 k2
168 -- > TyConApp PrimTyCon [...]
169 -- > TyVar kv   -- (during inference only)
170 -- > ForAll ... -- (for top-level coercions)
171 type Kind = Type
172
173 -- | "Super kinds", used to help encode 'Kind's as types.
174 -- Invariant: a super kind is always of this form:
175 --
176 -- > TyConApp SuperKindTyCon ...
177 type SuperKind = Type
178 \end{code}
179
180 Note [Equality-constrained types]
181 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
182 The type   forall ab. (a ~ [b]) => blah
183 is encoded like this:
184
185    ForAllTy (a:*) $ ForAllTy (b:*) $
186    ForAllTy (wild_co : a ~ [b]) $
187    blah
188
189 That is, the "(a ~ [b]) =>" part is encode as a for-all
190 type with a coercion variable that is never mentioned.
191
192 We could instead have used a FunTy with an EqPred on the 
193 left.  But we want 
194
195   * FunTy to mean RUN-TIME abstraction,
196     passing a real value at runtime, 
197
198   * ForAllTy to mean COMPILE-TIME abstraction, 
199     erased at runtime
200
201 -------------------------------------
202                 Note [PredTy]
203
204 \begin{code}
205 -- | A type of the form @PredTy p@ represents a value whose type is
206 -- the Haskell predicate @p@, where a predicate is what occurs before 
207 -- the @=>@ in a Haskell type.
208 -- It can be expanded into its representation, but: 
209 --
210 -- * The type checker must treat it as opaque
211 --
212 -- * The rest of the compiler treats it as transparent
213 --
214 -- Consider these examples:
215 --
216 -- > f :: (Eq a) => a -> Int
217 -- > g :: (?x :: Int -> Int) => a -> Int
218 -- > h :: (r\l) => {r} => {l::Int | r}
219 --
220 -- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\"
221 type PredType = Pred Type
222
223 data Pred a   -- Typically 'a' is instantiated with Type or Coercion
224   = ClassP Class [a]            -- ^ Class predicate e.g. @Eq a@
225   | IParam (IPName Name) a      -- ^ Implicit parameter e.g. @?x :: Int@
226   | EqPred a a                  -- ^ Equality predicate e.g @ty1 ~ ty2@
227   deriving (Data.Data, Data.Typeable, Data.Foldable, Data.Traversable, Functor)
228
229 -- | A collection of 'PredType's
230 type ThetaType = [PredType]
231 \end{code}
232
233 (We don't support TREX records yet, but the setup is designed
234 to expand to allow them.)
235
236 A Haskell qualified type, such as that for f,g,h above, is
237 represented using 
238         * a FunTy for the double arrow
239         * with a PredTy as the function argument
240
241 The predicate really does turn into a real extra argument to the
242 function.  If the argument has type (PredTy p) then the predicate p is
243 represented by evidence (a dictionary, for example, of type (predRepTy p).
244
245 Note [Equality predicates]
246 ~~~~~~~~~~~~~~~~~~~~~~~~~~
247         forall a b. (a ~ S b) => a -> b
248 could be represented by
249         ForAllTy a (ForAllTy b (FunTy (PredTy (EqPred a (S b))) ...))
250 OR
251         ForAllTy a (ForAllTy b (ForAllTy (c::PredTy (EqPred a (S b))) ...))
252
253 The latter is what we do.  (Unlike for class and implicit parameter
254 constraints, which do use FunTy.)
255
256 Reason:
257         * FunTy is always a *value* function
258         * ForAllTy is discarded at runtime
259
260 We often need to make a "wildcard" (c::PredTy..).  We always use the same
261 name (wildCoVarName), since it's not mentioned.
262
263
264 %************************************************************************
265 %*                                                                      *
266             Simple constructors
267 %*                                                                      *
268 %************************************************************************
269
270 These functions are here so that they can be used by TysPrim,
271 which in turn is imported by Type
272
273 \begin{code}
274 mkTyVarTy  :: TyVar   -> Type
275 mkTyVarTy  = TyVarTy
276
277 mkTyVarTys :: [TyVar] -> [Type]
278 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
279
280 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
281 -- Applies its arguments to the constructor from left to right
282 mkTyConApp :: TyCon -> [Type] -> Type
283 mkTyConApp tycon tys
284   | isFunTyCon tycon, [ty1,ty2] <- tys
285   = FunTy ty1 ty2
286
287   | otherwise
288   = TyConApp tycon tys
289
290 -- | Create the plain type constructor type which has been applied to no type arguments at all.
291 mkTyConTy :: TyCon -> Type
292 mkTyConTy tycon = mkTyConApp tycon []
293
294 isLiftedTypeKind :: Kind -> Bool
295 -- This function is here because it's used in the pretty printer
296 isLiftedTypeKind (TyConApp tc []) = tc `hasKey` liftedTypeKindTyConKey
297 isLiftedTypeKind _                = False
298
299 isCoercionKind :: Kind -> Bool
300 -- All coercions are of form (ty1 ~ ty2)
301 -- This function is here rather than in Coercion, because it
302 -- is used in a knot-tied way to enforce invariants in Var
303 isCoercionKind (PredTy (EqPred {})) = True
304 isCoercionKind _                    = False
305 \end{code}
306
307
308 %************************************************************************
309 %*                                                                      *
310                         Free variables of types and coercions
311 %*                                                                      *
312 %************************************************************************
313
314 \begin{code}
315 tyVarsOfPred :: PredType -> TyCoVarSet
316 tyVarsOfPred = varsOfPred tyVarsOfType
317
318 tyVarsOfTheta :: ThetaType -> TyCoVarSet
319 tyVarsOfTheta = varsOfTheta tyVarsOfType
320
321 tyVarsOfType :: Type -> VarSet
322 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
323 tyVarsOfType (TyVarTy v)         = unitVarSet v
324 tyVarsOfType (TyConApp _ tys)    = tyVarsOfTypes tys
325 tyVarsOfType (PredTy sty)        = varsOfPred tyVarsOfType sty
326 tyVarsOfType (FunTy arg res)     = tyVarsOfType arg `unionVarSet` tyVarsOfType res
327 tyVarsOfType (AppTy fun arg)     = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
328 tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
329
330 tyVarsOfTypes :: [Type] -> TyVarSet
331 tyVarsOfTypes tys = foldr (unionVarSet . tyVarsOfType) emptyVarSet tys
332
333 varsOfPred :: (a -> VarSet) -> Pred a -> VarSet
334 varsOfPred f (IParam _ ty)    = f ty
335 varsOfPred f (ClassP _ tys)   = foldr (unionVarSet . f) emptyVarSet tys
336 varsOfPred f (EqPred ty1 ty2) = f ty1 `unionVarSet` f ty2
337
338 varsOfTheta :: (a -> VarSet) -> [Pred a] -> VarSet
339 varsOfTheta f = foldr (unionVarSet . varsOfPred f) emptyVarSet
340
341 predSize :: (a -> Int) -> Pred a -> Int
342 predSize size (IParam _ t)   = 1 + size t
343 predSize size (ClassP _ ts)  = 1 + sum (map size ts)
344 predSize size (EqPred t1 t2) = size t1 + size t2
345 \end{code}
346
347 %************************************************************************
348 %*                                                                      *
349                         TyThing
350 %*                                                                      *
351 %************************************************************************
352
353 Despite the fact that DataCon has to be imported via a hi-boot route, 
354 this module seems the right place for TyThing, because it's needed for
355 funTyCon and all the types in TysPrim.
356
357 \begin{code}
358 -- | A typecheckable-thing, essentially anything that has a name
359 data TyThing = AnId     Id
360              | ADataCon DataCon
361              | ATyCon   TyCon
362              | ACoAxiom CoAxiom
363              | AClass   Class
364
365 instance Outputable TyThing where 
366   ppr = pprTyThing
367
368 pprTyThing :: TyThing -> SDoc
369 pprTyThing thing = pprTyThingCategory thing <+> quotes (ppr (getName thing))
370
371 pprTyThingCategory :: TyThing -> SDoc
372 pprTyThingCategory (ATyCon _)   = ptext (sLit "Type constructor")
373 pprTyThingCategory (ACoAxiom _) = ptext (sLit "Coercion axiom")
374 pprTyThingCategory (AClass _)   = ptext (sLit "Class")
375 pprTyThingCategory (AnId   _)   = ptext (sLit "Identifier")
376 pprTyThingCategory (ADataCon _) = ptext (sLit "Data constructor")
377
378 instance NamedThing TyThing where       -- Can't put this with the type
379   getName (AnId id)     = getName id    -- decl, because the DataCon instance
380   getName (ATyCon tc)   = getName tc    -- isn't visible there
381   getName (ACoAxiom cc) = getName cc
382   getName (AClass cl)   = getName cl
383   getName (ADataCon dc) = dataConName dc
384 \end{code}
385
386
387 %************************************************************************
388 %*                                                                      *
389                         Substitutions
390       Data type defined here to avoid unnecessary mutual recursion
391 %*                                                                      *
392 %************************************************************************
393
394 \begin{code}
395 -- | Type substitution
396 --
397 -- #tvsubst_invariant#
398 -- The following invariants must hold of a 'TvSubst':
399 -- 
400 -- 1. The in-scope set is needed /only/ to
401 -- guide the generation of fresh uniques
402 --
403 -- 2. In particular, the /kind/ of the type variables in 
404 -- the in-scope set is not relevant
405 --
406 -- 3. The substition is only applied ONCE! This is because
407 -- in general such application will not reached a fixed point.
408 data TvSubst            
409   = TvSubst InScopeSet  -- The in-scope type variables
410             TvSubstEnv  -- Substitution of types
411         -- See Note [Apply Once]
412         -- and Note [Extending the TvSubstEnv]
413
414 -- | A substitition of 'Type's for 'TyVar's
415 type TvSubstEnv = TyVarEnv Type
416         -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
417         -- invariant discussed in Note [Apply Once]), and also independently
418         -- in the middle of matching, and unification (see Types.Unify)
419         -- So you have to look at the context to know if it's idempotent or
420         -- apply-once or whatever
421 \end{code}
422
423 Note [Apply Once]
424 ~~~~~~~~~~~~~~~~~
425 We use TvSubsts to instantiate things, and we might instantiate
426         forall a b. ty
427 \with the types
428         [a, b], or [b, a].
429 So the substition might go [a->b, b->a].  A similar situation arises in Core
430 when we find a beta redex like
431         (/\ a /\ b -> e) b a
432 Then we also end up with a substition that permutes type variables. Other
433 variations happen to; for example [a -> (a, b)].  
434
435         ***************************************************
436         *** So a TvSubst must be applied precisely once ***
437         ***************************************************
438
439 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
440 we use during unifications, it must not be repeatedly applied.
441
442 Note [Extending the TvSubst]
443 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
444 See #tvsubst_invariant# for the invariants that must hold.
445
446 This invariant allows a short-cut when the TvSubstEnv is empty:
447 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
448 then (substTy subst ty) does nothing.
449
450 For example, consider:
451         (/\a. /\b:(a~Int). ...b..) Int
452 We substitute Int for 'a'.  The Unique of 'b' does not change, but
453 nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
454
455 This invariant has several crucial consequences:
456
457 * In substTyVarBndr, we need extend the TvSubstEnv 
458         - if the unique has changed
459         - or if the kind has changed
460
461 * In substTyVar, we do not need to consult the in-scope set;
462   the TvSubstEnv is enough
463
464 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
465 \end{code}
466
467
468
469 %************************************************************************
470 %*                                                                      *
471                    Pretty-printing types
472
473        Defined very early because of debug printing in assertions
474 %*                                                                      *
475 %************************************************************************
476
477 @pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
478 defined to use this.  @pprParendType@ is the same, except it puts
479 parens around the type, except for the atomic cases.  @pprParendType@
480 works just by setting the initial context precedence very high.
481
482 \begin{code}
483 data Prec = TopPrec     -- No parens
484           | FunPrec     -- Function args; no parens for tycon apps
485           | TyConPrec   -- Tycon args; no parens for atomic
486           deriving( Eq, Ord )
487
488 maybeParen :: Prec -> Prec -> SDoc -> SDoc
489 maybeParen ctxt_prec inner_prec pretty
490   | ctxt_prec < inner_prec = pretty
491   | otherwise              = parens pretty
492
493 ------------------
494 pprType, pprParendType :: Type -> SDoc
495 pprType       ty = ppr_type TopPrec ty
496 pprParendType ty = ppr_type TyConPrec ty
497
498 pprKind, pprParendKind :: Kind -> SDoc
499 pprKind       = pprType
500 pprParendKind = pprParendType
501
502 ------------------
503 pprPredTy :: PredType -> SDoc
504 pprPredTy = pprPred ppr_type
505
506 pprPred :: (Prec -> a -> SDoc) -> Pred a -> SDoc
507 pprPred pp (ClassP cls tys) = ppr_class_pred pp cls tys
508 pprPred pp (IParam ip ty)   = ppr ip <> dcolon <> pp TopPrec ty
509 pprPred pp (EqPred ty1 ty2) = ppr_eq_pred pp (Pair ty1 ty2)
510
511 ------------
512 pprEqPred :: Pair Type -> SDoc
513 pprEqPred = ppr_eq_pred ppr_type
514
515 ppr_eq_pred :: (Prec -> a -> SDoc) -> Pair a -> SDoc
516 ppr_eq_pred pp (Pair ty1 ty2) = sep [ pp FunPrec ty1
517                                     , nest 2 (ptext (sLit "~"))
518                                     , pp FunPrec ty2]
519                                -- Precedence looks like (->) so that we get
520                                --    Maybe a ~ Bool
521                                --    (a->a) ~ Bool
522                                -- Note parens on the latter!
523
524 ------------
525 pprClassPred :: Class -> [Type] -> SDoc
526 pprClassPred = ppr_class_pred ppr_type
527
528 ppr_class_pred :: (Prec -> a -> SDoc) -> Class -> [a] -> SDoc
529 ppr_class_pred pp clas tys = pprTypeNameApp TopPrec pp (getName clas) tys
530
531 ------------
532 pprTheta :: ThetaType -> SDoc
533 -- pprTheta [pred] = pprPred pred        -- I'm in two minds about this
534 pprTheta theta  = parens (sep (punctuate comma (map pprPredTy theta)))
535
536 pprThetaArrowTy :: ThetaType -> SDoc
537 pprThetaArrowTy = pprThetaArrow ppr_type
538
539 pprThetaArrow :: (Prec -> a -> SDoc) -> [Pred a] -> SDoc
540 pprThetaArrow _ []      = empty
541 pprThetaArrow pp [pred]
542       | noParenPred pred = pprPred pp pred <+> darrow
543 pprThetaArrow pp preds   = parens (sep (punctuate comma (map (pprPred pp) preds)))
544                             <+> darrow
545
546 noParenPred :: Pred a -> Bool
547 -- A predicate that can appear without parens before a "=>"
548 --       C a => a -> a
549 --       a~b => a -> b
550 -- But   (?x::Int) => Int -> Int
551 noParenPred (ClassP {}) = True
552 noParenPred (EqPred {}) = True
553 noParenPred (IParam {}) = False
554
555 ------------------
556 instance Outputable Type where
557     ppr ty = pprType ty
558
559 instance Outputable (Pred Type) where
560     ppr = pprPredTy   -- Not for arbitrary (Pred a), because the
561                       -- (Outputable a) doesn't give precedence
562
563 instance Outputable name => OutputableBndr (IPName name) where
564     pprBndr _ n = ppr n -- Simple for now
565
566 ------------------
567         -- OK, here's the main printer
568
569 ppr_type :: Prec -> Type -> SDoc
570 ppr_type _ (TyVarTy tv)         -- Note [Infix type variables]
571   | isSymOcc (getOccName tv)  = parens (ppr tv)
572   | otherwise                 = ppr tv
573 ppr_type p (PredTy pred)      = maybeParen p TyConPrec $
574                                 ifPprDebug (ptext (sLit "<pred>")) <> (pprPredTy pred)
575 ppr_type p (TyConApp tc tys)  = pprTcApp p ppr_type tc tys
576
577 ppr_type p (AppTy t1 t2) = maybeParen p TyConPrec $
578                            pprType t1 <+> ppr_type TyConPrec t2
579
580 ppr_type p ty@(ForAllTy {})        = ppr_forall_type p ty
581 ppr_type p ty@(FunTy (PredTy _) _) = ppr_forall_type p ty
582
583 ppr_type p (FunTy ty1 ty2)
584   = pprArrowChain p (ppr_type FunPrec ty1 : ppr_fun_tail ty2)
585   where
586     -- We don't want to lose synonyms, so we mustn't use splitFunTys here.
587     ppr_fun_tail (FunTy ty1 ty2)
588       | not (is_pred ty1) = ppr_type FunPrec ty1 : ppr_fun_tail ty2
589     ppr_fun_tail other_ty = [ppr_type TopPrec other_ty]
590
591     is_pred (PredTy {}) = True
592     is_pred _           = False
593
594 ppr_forall_type :: Prec -> Type -> SDoc
595 ppr_forall_type p ty
596   = maybeParen p FunPrec $
597     sep [pprForAll tvs, pprThetaArrowTy ctxt, pprType tau]
598   where
599     (tvs,  rho) = split1 [] ty
600     (ctxt, tau) = split2 [] rho
601
602     split1 tvs (ForAllTy tv ty) = split1 (tv:tvs) ty
603     split1 tvs ty               = (reverse tvs, ty)
604  
605     split2 ps (PredTy p `FunTy` ty) = split2 (p:ps) ty
606     split2 ps ty                    = (reverse ps, ty)
607
608 -------------------
609 pprForAll :: [TyVar] -> SDoc
610 pprForAll []  = empty
611 pprForAll tvs = ptext (sLit "forall") <+> sep (map pprTvBndr tvs) <> dot
612
613 pprTvBndr :: TyVar -> SDoc
614 pprTvBndr tv
615   | isLiftedTypeKind kind = ppr tv
616   | otherwise             = parens (ppr tv <+> dcolon <+> pprKind kind)
617   where
618     kind = tyVarKind tv
619 \end{code}
620
621 Note [Infix type variables]
622 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
623 With TypeOperators you can say
624
625    f :: (a ~> b) -> b
626
627 and the (~>) is considered a type variable.  However, the type
628 pretty-printer in this module will just see (a ~> b) as
629
630    App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b")
631
632 So it'll print the type in prefix form.  To avoid confusion we must
633 remember to parenthesise the operator, thus
634
635    (~>) a b -> b
636
637 See Trac #2766.
638
639 \begin{code}
640 pprTcApp :: Prec -> (Prec -> a -> SDoc) -> TyCon -> [a] -> SDoc
641 pprTcApp _ _ tc []      -- No brackets for SymOcc
642   = pp_nt_debug <> ppr tc
643   where
644    pp_nt_debug | isNewTyCon tc = ifPprDebug (if isRecursiveTyCon tc 
645                                              then ptext (sLit "<recnt>")
646                                              else ptext (sLit "<nt>"))
647                | otherwise     = empty
648
649 pprTcApp _ pp tc [ty]
650   | tc `hasKey` listTyConKey = brackets (pp TopPrec ty)
651   | tc `hasKey` parrTyConKey = ptext (sLit "[:") <> pp TopPrec ty <> ptext (sLit ":]")
652   | tc `hasKey` liftedTypeKindTyConKey   = ptext (sLit "*")
653   | tc `hasKey` unliftedTypeKindTyConKey = ptext (sLit "#")
654   | tc `hasKey` openTypeKindTyConKey     = ptext (sLit "(?)")
655   | tc `hasKey` ubxTupleKindTyConKey     = ptext (sLit "(#)")
656   | tc `hasKey` argTypeKindTyConKey      = ptext (sLit "??")
657
658 pprTcApp p pp tc tys
659   | isTupleTyCon tc && tyConArity tc == length tys
660   = tupleParens (tupleTyConBoxity tc) (sep (punctuate comma (map (pp TopPrec) tys)))
661   | otherwise
662   = pprTypeNameApp p pp (getName tc) tys
663
664 ----------------
665 pprTypeApp :: NamedThing a => a -> [Type] -> SDoc
666 -- The first arg is the tycon, or sometimes class
667 -- Print infix if the tycon/class looks like an operator
668 pprTypeApp tc tys = pprTypeNameApp TopPrec ppr_type (getName tc) tys
669
670 pprTypeNameApp :: Prec -> (Prec -> a -> SDoc) -> Name -> [a] -> SDoc
671 -- Used for classes and coercions as well as types; that's why it's separate from pprTcApp
672 pprTypeNameApp p pp tc tys
673   | is_sym_occ           -- Print infix if possible
674   , [ty1,ty2] <- tys  -- We know nothing of precedence though
675   = maybeParen p FunPrec $
676     sep [pp FunPrec ty1, pprInfixVar True (ppr tc) <+> pp FunPrec ty2]
677   | otherwise
678   = pprPrefixApp p (pprPrefixVar is_sym_occ (ppr tc)) (map (pp TyConPrec) tys)
679   where
680     is_sym_occ = isSymOcc (getOccName tc)
681
682 ----------------
683 pprPrefixApp :: Prec -> SDoc -> [SDoc] -> SDoc
684 pprPrefixApp p pp_fun pp_tys = maybeParen p TyConPrec $
685                                hang pp_fun 2 (sep pp_tys)
686
687 ----------------
688 pprArrowChain :: Prec -> [SDoc] -> SDoc
689 -- pprArrowChain p [a,b,c]  generates   a -> b -> c
690 pprArrowChain _ []         = empty
691 pprArrowChain p (arg:args) = maybeParen p FunPrec $
692                              sep [arg, sep (map (arrow <+>) args)]
693 \end{code}
694