2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[HsTypes]{Abstract syntax: user-defined types}
8 HsType(..), HsTyVarBndr(..), HsTyOp(..),
9 , HsContext, HsPred(..)
10 , HsTupCon(..), hsTupParens, mkHsTupCon,
12 , mkHsForAllTy, mkHsDictTy, mkHsIParamTy
13 , hsTyVarName, hsTyVarNames, replaceTyVarName
17 , PostTcType, placeHolderType,
20 , SyntaxName, placeHolderName,
23 , pprParendHsType, pprHsForAll, pprHsContext, ppr_hs_context, pprHsTyVarBndr
25 -- Equality over Hs things
26 , EqHsEnv, emptyEqHsEnv, extendEqHsEnv,
27 , eqWithHsTyVars, eq_hsVar, eq_hsVars, eq_hsTyVars, eq_hsType, eq_hsContext, eqListBy
29 -- Converting from Type to HsType
30 , toHsType, toHsTyVar, toHsTyVars, toHsContext, toHsFDs
33 #include "HsVersions.h"
35 import Class ( FunDep )
36 import TcType ( Type, Kind, ThetaType, SourceType(..),
37 tcSplitSigmaTy, liftedTypeKind, eqKind, tcEqType
39 import TypeRep ( Type(..), TyNote(..) ) -- toHsType sees the representation
40 import TyCon ( isTupleTyCon, tupleTyConBoxity, tyConArity, isNewTyCon, getSynTyConDefn )
41 import RdrName ( mkUnqual )
42 import Name ( Name, getName, mkInternalName )
43 import OccName ( NameSpace, mkVarOcc, tvName )
44 import Var ( TyVar, tyVarKind )
45 import Subst ( substTyWith )
46 import PprType ( {- instance Outputable Kind -}, pprParendKind, pprKind )
47 import BasicTypes ( Boxity(..), Arity, IPName, tupleParens )
48 import PrelNames ( listTyConKey, parrTyConKey,
50 import SrcLoc ( noSrcLoc )
51 import Util ( eqListBy, lengthIs )
57 %************************************************************************
59 \subsection{Annotating the syntax}
61 %************************************************************************
64 type PostTcType = Type -- Used for slots in the abstract syntax
65 -- where we want to keep slot for a type
66 -- to be added by the type checker...but
67 -- before typechecking it's just bogus
69 placeHolderType :: PostTcType -- Used before typechecking
70 placeHolderType = panic "Evaluated the place holder for a PostTcType"
73 type SyntaxName = Name -- These names are filled in by the renamer
74 -- Before then they are a placeHolderName (so that
75 -- we can still print the HsSyn)
76 -- They correspond to "rebindable syntax";
77 -- See RnEnv.lookupSyntaxName
79 placeHolderName :: SyntaxName
80 placeHolderName = mkInternalName unboundKey
81 (mkVarOcc FSLIT("syntaxPlaceHolder"))
86 %************************************************************************
88 \subsection{Data types}
90 %************************************************************************
92 This is the syntax for types as seen in type signatures.
95 type HsContext name = [HsPred name]
97 data HsPred name = HsClassP name [HsType name]
98 | HsIParam (IPName name) (HsType name)
101 = HsForAllTy (Maybe [HsTyVarBndr name]) -- Nothing for implicitly quantified signatures
105 | HsTyVar name -- Type variable or type constructor
107 | HsAppTy (HsType name)
110 | HsFunTy (HsType name) -- function type
113 | HsListTy (HsType name) -- Element type
115 | HsPArrTy (HsType name) -- Elem. type of parallel array: [:t:]
118 [HsType name] -- Element types (length gives arity)
120 | HsOpTy (HsType name) (HsTyOp name) (HsType name)
122 | HsParTy (HsType name)
123 -- Parenthesis preserved for the precedence re-arrangement in RnTypes
124 -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
126 -- However, NB that toHsType doesn't add HsParTys (in an effort to keep
127 -- interface files smaller), so when printing a HsType we may need to
130 | HsNumTy Integer -- Generics only
132 -- these next two are only used in interfaces
133 | HsPredTy (HsPred name)
135 | HsKindSig (HsType name) -- (ty :: kind)
136 Kind -- A type with a kind signature
139 data HsTyOp name = HsArrow | HsTyOp name
140 -- Function arrows from *source* get read in as HsOpTy t1 HsArrow t2
141 -- But when we generate or parse interface files, we use HsFunTy.
142 -- This keeps interfaces a bit smaller, because there are a lot of arrows
144 -----------------------
145 data HsTupCon = HsTupCon Boxity Arity
147 instance Eq HsTupCon where
148 (HsTupCon b1 a1) == (HsTupCon b2 a2) = b1==b2 && a1==a2
150 mkHsTupCon :: NameSpace -> Boxity -> [a] -> HsTupCon
151 mkHsTupCon space boxity args = HsTupCon boxity (length args)
153 hsTupParens :: HsTupCon -> SDoc -> SDoc
154 hsTupParens (HsTupCon b _) p = tupleParens b p
156 -----------------------
157 -- Combine adjacent for-alls.
158 -- The following awkward situation can happen otherwise:
159 -- f :: forall a. ((Num a) => Int)
160 -- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
161 -- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
162 -- but the export list abstracts f wrt [a]. Disaster.
164 -- A valid type must have one for-all at the top of the type, or of the fn arg types
166 mkHsForAllTy mtvs [] ty = mk_forall_ty mtvs ty
167 mkHsForAllTy mtvs ctxt ty = HsForAllTy mtvs ctxt ty
169 -- mk_forall_ty makes a pure for-all type (no context)
170 mk_forall_ty (Just []) ty = ty -- Explicit for-all with no tyvars
171 mk_forall_ty mtvs1 (HsParTy ty) = mk_forall_ty mtvs1 ty
172 mk_forall_ty mtvs1 (HsForAllTy mtvs2 ctxt ty) = mkHsForAllTy (mtvs1 `plus` mtvs2) ctxt ty
173 mk_forall_ty mtvs1 ty = HsForAllTy mtvs1 [] ty
175 mtvs1 `plus` Nothing = mtvs1
176 Nothing `plus` mtvs2 = mtvs2
177 (Just tvs1) `plus` (Just tvs2) = Just (tvs1 ++ tvs2)
179 mkHsDictTy cls tys = HsPredTy (HsClassP cls tys)
180 mkHsIParamTy v ty = HsPredTy (HsIParam v ty)
182 data HsTyVarBndr name
184 | IfaceTyVar name Kind
185 -- *** NOTA BENE *** A "monotype" in a pragma can have
186 -- for-alls in it, (mostly to do with dictionaries). These
187 -- must be explicitly Kinded.
189 hsTyVarName (UserTyVar n) = n
190 hsTyVarName (IfaceTyVar n _) = n
192 hsTyVarNames tvs = map hsTyVarName tvs
194 replaceTyVarName :: HsTyVarBndr name1 -> name2 -> HsTyVarBndr name2
195 replaceTyVarName (UserTyVar n) n' = UserTyVar n'
196 replaceTyVarName (IfaceTyVar n k) n' = IfaceTyVar n' k
204 -> ([HsTyVarBndr name], HsContext name, name, [HsType name])
205 -- Split up an instance decl type, returning the pieces
207 -- In interface files, the instance declaration head is created
208 -- by HsTypes.toHsType, which does not guarantee to produce a
209 -- HsForAllTy. For example, if we had the weird decl
210 -- instance Foo T => Foo [T]
211 -- then we'd get the instance type
213 -- So when colleting the instance context, to be on the safe side
214 -- we gather predicate arguments
216 -- For source code, the parser ensures the type will have the right shape.
217 -- (e.g. see ParseUtil.checkInstType)
219 splitHsInstDeclTy inst_ty
221 HsForAllTy (Just tvs) cxt1 tau
222 -> (tvs, cxt1++cxt2, cls, tys)
224 (cxt2, cls, tys) = split_tau tau
226 other -> ([], cxt2, cls, tys)
228 (cxt2, cls, tys) = split_tau inst_ty
231 split_tau (HsFunTy (HsPredTy p) ty) = (p:ps, cls, tys)
233 (ps, cls, tys) = split_tau ty
234 split_tau (HsPredTy (HsClassP cls tys)) = ([], cls,tys)
235 split_tau other = pprPanic "splitHsInstDeclTy" (ppr inst_ty)
239 %************************************************************************
241 \subsection{Pretty printing}
243 %************************************************************************
245 NB: these types get printed into interface files, so
246 don't change the printing format lightly
249 instance (Outputable name) => Outputable (HsType name) where
250 ppr ty = pprHsType ty
252 instance (Outputable name) => Outputable (HsTyOp name) where
253 ppr HsArrow = ftext FSLIT("->")
254 ppr (HsTyOp n) = ppr n
256 instance (Outputable name) => Outputable (HsTyVarBndr name) where
257 ppr (UserTyVar name) = ppr name
258 ppr (IfaceTyVar name kind) = pprHsTyVarBndr name kind
260 instance Outputable name => Outputable (HsPred name) where
261 ppr (HsClassP clas tys) = ppr clas <+> hsep (map pprParendHsType tys)
262 ppr (HsIParam n ty) = hsep [ppr n, dcolon, ppr ty]
264 pprHsTyVarBndr :: Outputable name => name -> Kind -> SDoc
265 pprHsTyVarBndr name kind | kind `eqKind` liftedTypeKind = ppr name
266 | otherwise = hsep [ppr name, dcolon, pprParendKind kind]
268 pprHsForAll [] [] = empty
270 -- This printer is used for both interface files and
271 -- printing user types in error messages; and alas the
272 -- two use slightly different syntax. Ah well.
273 = getPprStyle $ \ sty ->
274 if userStyle sty then
275 ptext SLIT("forall") <+> interppSP tvs <> dot <+>
276 -- **! ToDo: want to hide uvars from user, but not enough info
277 -- in a HsTyVarBndr name (see PprType). KSW 2000-10.
279 else -- Used in interfaces
280 ptext SLIT("__forall") <+> interppSP tvs <+>
281 ppr_hs_context cxt <+> ptext SLIT("=>")
283 pprHsContext :: (Outputable name) => HsContext name -> SDoc
284 pprHsContext [] = empty
285 pprHsContext cxt = ppr_hs_context cxt <+> ptext SLIT("=>")
287 ppr_hs_context [] = empty
288 ppr_hs_context cxt = parens (interpp'SP cxt)
292 pREC_TOP = (0 :: Int) -- type in ParseIface.y
293 pREC_FUN = (1 :: Int) -- btype in ParseIface.y
294 -- Used for LH arg of (->)
295 pREC_OP = (2 :: Int) -- Used for arg of any infix operator
296 -- (we don't keep their fixities around)
297 pREC_CON = (3 :: Int) -- Used for arg of type applicn:
298 -- always parenthesise unless atomic
300 maybeParen :: Int -- Precedence of context
301 -> Int -- Precedence of top-level operator
302 -> SDoc -> SDoc -- Wrap in parens if (ctxt >= op)
303 maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p
306 -- printing works more-or-less as for Types
308 pprHsType, pprParendHsType :: (Outputable name) => HsType name -> SDoc
310 pprHsType ty = ppr_mono_ty pREC_TOP (de_paren ty)
311 pprParendHsType ty = ppr_mono_ty pREC_CON ty
313 -- Remove outermost HsParTy parens before printing a type
314 de_paren (HsParTy ty) = de_paren ty
317 ppr_mono_ty ctxt_prec (HsForAllTy maybe_tvs ctxt ty)
318 = maybeParen ctxt_prec pREC_FUN $
319 sep [pp_header, pprHsType ty]
321 pp_header = case maybe_tvs of
322 Just tvs -> pprHsForAll tvs ctxt
323 Nothing -> pprHsContext ctxt
325 ppr_mono_ty ctxt_prec (HsTyVar name) = ppr name
326 ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2) = ppr_fun_ty ctxt_prec ty1 ty2
327 ppr_mono_ty ctxt_prec (HsTupleTy con tys) = hsTupParens con (interpp'SP tys)
328 ppr_mono_ty ctxt_prec (HsKindSig ty kind) = parens (ppr_mono_ty pREC_TOP ty <+> dcolon <+> pprKind kind)
329 ppr_mono_ty ctxt_prec (HsListTy ty) = brackets (ppr_mono_ty pREC_TOP ty)
330 ppr_mono_ty ctxt_prec (HsPArrTy ty) = pabrackets (ppr_mono_ty pREC_TOP ty)
331 ppr_mono_ty ctxt_prec (HsPredTy pred) = braces (ppr pred)
332 ppr_mono_ty ctxt_prec (HsNumTy n) = integer n -- generics only
334 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
335 = maybeParen ctxt_prec pREC_CON $
336 hsep [ppr_mono_ty pREC_FUN fun_ty, ppr_mono_ty pREC_CON arg_ty]
338 ppr_mono_ty ctxt_prec (HsOpTy ty1 HsArrow ty2)
339 = ppr_fun_ty ctxt_prec ty1 ty2
341 ppr_mono_ty ctxt_prec (HsOpTy ty1 op ty2)
342 = maybeParen ctxt_prec pREC_OP $
343 ppr_mono_ty pREC_OP ty1 <+> ppr op <+> ppr_mono_ty pREC_OP ty2
345 ppr_mono_ty ctxt_prec (HsParTy ty)
346 = parens (ppr_mono_ty pREC_TOP ty)
347 -- Put the parens in where the user did
348 -- But we still use the precedence stuff to add parens because
349 -- toHsType doesn't put in any HsParTys, so we may still need them
351 --------------------------
352 ppr_fun_ty ctxt_prec ty1 ty2
353 = let p1 = ppr_mono_ty pREC_FUN ty1
354 p2 = ppr_mono_ty pREC_TOP ty2
356 maybeParen ctxt_prec pREC_FUN $
357 sep [p1, ptext SLIT("->") <+> p2]
359 --------------------------
360 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
364 %************************************************************************
366 \subsection{Converting from Type to HsType}
368 %************************************************************************
370 @toHsType@ converts from a Type to a HsType, making the latter look as
371 user-friendly as possible. Notably, it uses synonyms where possible, and
372 expresses overloaded functions using the '=>' context part of a HsForAllTy.
375 toHsTyVar :: TyVar -> HsTyVarBndr Name
376 toHsTyVar tv = IfaceTyVar (getName tv) (tyVarKind tv)
378 toHsTyVars tvs = map toHsTyVar tvs
380 toHsType :: Type -> HsType Name
381 -- This function knows the representation of types
382 toHsType (TyVarTy tv) = HsTyVar (getName tv)
383 toHsType (FunTy arg res) = HsFunTy (toHsType arg) (toHsType res)
384 toHsType (AppTy fun arg) = HsAppTy (toHsType fun) (toHsType arg)
386 toHsType (NoteTy (SynNote ty@(TyConApp tycon tyargs)) real_ty)
387 | isNewTyCon tycon = toHsType ty
388 | syn_matches = toHsType ty -- Use synonyms if possible!!
391 pprTrace "WARNING: synonym info lost in .hi file for " (ppr syn_ty) $
393 toHsType real_ty -- but drop it if not.
395 syn_matches = ty_from_syn `tcEqType` real_ty
396 (tyvars,syn_ty) = getSynTyConDefn tycon
397 ty_from_syn = substTyWith tyvars tyargs syn_ty
399 -- We only use the type synonym in the file if this doesn't cause
400 -- us to lose important information. This matters for usage
401 -- annotations. It's an issue if some of the args to the synonym
402 -- have arrows in them, or if the synonym's RHS has an arrow; for
403 -- example, with nofib/real/ebnf2ps/ in Parsers.using.
405 -- **! It would be nice if when this test fails we could still
406 -- write the synonym in as a Note, so we don't lose the info for
407 -- error messages, but it's too much work for right now.
410 toHsType (NoteTy _ ty) = toHsType ty
412 toHsType (SourceTy (NType tc tys)) = foldl HsAppTy (HsTyVar (getName tc)) (map toHsType tys)
413 toHsType (SourceTy pred) = HsPredTy (toHsPred pred)
415 toHsType ty@(TyConApp tc tys) -- Must be saturated because toHsType's arg is of kind *
416 | not saturated = generic_case
417 | isTupleTyCon tc = HsTupleTy (HsTupCon (tupleTyConBoxity tc) (tyConArity tc)) tys'
418 | tc `hasKey` listTyConKey = HsListTy (head tys')
419 | tc `hasKey` parrTyConKey = HsPArrTy (head tys')
420 | otherwise = generic_case
422 generic_case = foldl HsAppTy (HsTyVar (getName tc)) tys'
423 tys' = map toHsType tys
424 saturated = tys `lengthIs` tyConArity tc
426 toHsType ty@(ForAllTy _ _) = case tcSplitSigmaTy ty of
427 (tvs, preds, tau) -> HsForAllTy (Just (map toHsTyVar tvs))
431 toHsPred (ClassP cls tys) = HsClassP (getName cls) (map toHsType tys)
432 toHsPred (IParam n ty) = HsIParam n (toHsType ty)
434 toHsContext :: ThetaType -> HsContext Name
435 toHsContext theta = map toHsPred theta
437 toHsFDs :: [FunDep TyVar] -> [FunDep Name]
438 toHsFDs fds = [(map getName ns, map getName ms) | (ns,ms) <- fds]
442 %************************************************************************
444 \subsection{Comparison}
446 %************************************************************************
449 instance Ord a => Eq (HsType a) where
450 -- The Ord is needed because we keep a
451 -- finite map of variables to variables
452 (==) a b = eq_hsType emptyEqHsEnv a b
454 instance Ord a => Eq (HsPred a) where
455 (==) a b = eq_hsPred emptyEqHsEnv a b
457 eqWithHsTyVars :: Ord name =>
458 [HsTyVarBndr name] -> [HsTyVarBndr name]
459 -> (EqHsEnv name -> Bool) -> Bool
460 eqWithHsTyVars = eq_hsTyVars emptyEqHsEnv
464 type EqHsEnv n = FiniteMap n n
465 -- Tracks the mapping from L-variables to R-variables
467 eq_hsVar :: Ord n => EqHsEnv n -> n -> n -> Bool
468 eq_hsVar env n1 n2 = case lookupFM env n1 of
472 extendEqHsEnv env n1 n2
474 | otherwise = addToFM env n1 n2
476 emptyEqHsEnv :: EqHsEnv n
477 emptyEqHsEnv = emptyFM
480 We do define a specialised equality for these \tr{*Type} types; used
481 in checking interfaces.
485 eq_hsTyVars env [] [] k = k env
486 eq_hsTyVars env (tv1:tvs1) (tv2:tvs2) k = eq_hsTyVar env tv1 tv2 $ \ env ->
487 eq_hsTyVars env tvs1 tvs2 k
488 eq_hsTyVars env _ _ _ = False
490 eq_hsTyVar env (UserTyVar v1) (UserTyVar v2) k = k (extendEqHsEnv env v1 v2)
491 eq_hsTyVar env (IfaceTyVar v1 k1) (IfaceTyVar v2 k2) k = k1 `eqKind` k2 && k (extendEqHsEnv env v1 v2)
492 eq_hsTyVar env _ _ _ = False
494 eq_hsVars env [] [] k = k env
495 eq_hsVars env (v1:bs1) (v2:bs2) k = eq_hsVars (extendEqHsEnv env v1 v2) bs1 bs2 k
496 eq_hsVars env _ _ _ = False
501 eq_hsTypes env = eqListBy (eq_hsType env)
504 eq_hsType env (HsForAllTy tvs1 c1 t1) (HsForAllTy tvs2 c2 t2)
505 = eq_tvs tvs1 tvs2 $ \env ->
506 eq_hsContext env c1 c2 &&
509 eq_tvs Nothing (Just _) k = False
510 eq_tvs Nothing Nothing k = k env
511 eq_tvs (Just _) Nothing k = False
512 eq_tvs (Just tvs1) (Just tvs2) k = eq_hsTyVars env tvs1 tvs2 k
514 eq_hsType env (HsTyVar n1) (HsTyVar n2)
517 eq_hsType env (HsTupleTy c1 tys1) (HsTupleTy c2 tys2)
518 = (c1 == c2) && eq_hsTypes env tys1 tys2
520 eq_hsType env (HsListTy ty1) (HsListTy ty2)
521 = eq_hsType env ty1 ty2
523 eq_hsType env (HsKindSig ty1 k1) (HsKindSig ty2 k2)
524 = eq_hsType env ty1 ty2 && k1 `eqKind` k2
526 eq_hsType env (HsPArrTy ty1) (HsPArrTy ty2)
527 = eq_hsType env ty1 ty2
529 eq_hsType env (HsAppTy fun_ty1 arg_ty1) (HsAppTy fun_ty2 arg_ty2)
530 = eq_hsType env fun_ty1 fun_ty2 && eq_hsType env arg_ty1 arg_ty2
532 eq_hsType env (HsFunTy a1 b1) (HsFunTy a2 b2)
533 = eq_hsType env a1 a2 && eq_hsType env b1 b2
535 eq_hsType env (HsPredTy p1) (HsPredTy p2)
536 = eq_hsPred env p1 p2
538 eq_hsType env (HsOpTy lty1 op1 rty1) (HsOpTy lty2 op2 rty2)
539 = eq_hsOp env op1 op2 && eq_hsType env lty1 lty2 && eq_hsType env rty1 rty2
541 eq_hsType env ty1 ty2 = False
544 eq_hsOp env (HsTyOp n1) (HsTyOp n2) = eq_hsVar env n1 n2
545 eq_hsOp env HsArrow HsArrow = True
546 eq_hsOp env op1 op2 = False
549 eq_hsContext env a b = eqListBy (eq_hsPred env) a b
552 eq_hsPred env (HsClassP c1 tys1) (HsClassP c2 tys2)
553 = c1 == c2 && eq_hsTypes env tys1 tys2
554 eq_hsPred env (HsIParam n1 ty1) (HsIParam n2 ty2)
555 = n1 == n2 && eq_hsType env ty1 ty2
556 eq_hsPred env _ _ = False