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,
13 , mkHsForAllTy, mkHsDictTy, mkHsIParamTy
14 , hsTyVarName, hsTyVarNames, replaceTyVarName
18 , PostTcType, placeHolderType,
21 , SyntaxName, placeHolderName,
24 , pprParendHsType, pprHsForAll, pprHsContext, ppr_hs_context, pprHsTyVarBndr
26 -- Equality over Hs things
27 , EqHsEnv, emptyEqHsEnv, extendEqHsEnv,
28 , eqWithHsTyVars, eq_hsVar, eq_hsVars, eq_hsTyVars, eq_hsType, eq_hsContext, eqListBy
30 -- Converting from Type to HsType
31 , toHsType, toHsTyVar, toHsTyVars, toHsContext, toHsFDs
34 #include "HsVersions.h"
36 import Class ( FunDep )
37 import TcType ( Type, Kind, ThetaType, SourceType(..),
38 tcSplitSigmaTy, liftedTypeKind, eqKind, tcEqType
40 import TypeRep ( Type(..), TyNote(..) ) -- toHsType sees the representation
41 import TyCon ( isTupleTyCon, tupleTyConBoxity, tyConArity, isNewTyCon, getSynTyConDefn )
42 import RdrName ( RdrName, mkUnqual )
43 import Name ( Name, getName, mkInternalName )
44 import OccName ( NameSpace, mkVarOcc, tvName )
45 import Var ( TyVar, tyVarKind )
46 import Subst ( substTyWith )
47 import PprType ( {- instance Outputable Kind -}, pprParendKind, pprKind )
48 import BasicTypes ( Boxity(..), Arity, IPName, tupleParens )
49 import PrelNames ( listTyConKey, parrTyConKey,
50 usOnceTyConKey, usManyTyConKey, hasKey, unboundKey,
51 usOnceTyConName, usManyTyConName )
52 import SrcLoc ( noSrcLoc )
53 import Util ( eqListBy, lengthIs )
59 %************************************************************************
61 \subsection{Annotating the syntax}
63 %************************************************************************
66 type PostTcType = Type -- Used for slots in the abstract syntax
67 -- where we want to keep slot for a type
68 -- to be added by the type checker...but
69 -- before typechecking it's just bogus
71 placeHolderType :: PostTcType -- Used before typechecking
72 placeHolderType = panic "Evaluated the place holder for a PostTcType"
75 type SyntaxName = Name -- These names are filled in by the renamer
76 -- Before then they are a placeHolderName (so that
77 -- we can still print the HsSyn)
78 -- They correspond to "rebindable syntax";
79 -- See RnEnv.lookupSyntaxName
81 placeHolderName :: SyntaxName
82 placeHolderName = mkInternalName unboundKey
83 (mkVarOcc FSLIT("syntaxPlaceHolder"))
88 %************************************************************************
90 \subsection{Data types}
92 %************************************************************************
94 This is the syntax for types as seen in type signatures.
97 type HsContext name = [HsPred name]
99 data HsPred name = HsClassP name [HsType name]
100 | HsIParam (IPName name) (HsType name)
103 = HsForAllTy (Maybe [HsTyVarBndr name]) -- Nothing for implicitly quantified signatures
107 | HsTyVar name -- Type variable or type constructor
109 | HsAppTy (HsType name)
112 | HsFunTy (HsType name) -- function type
115 | HsListTy (HsType name) -- Element type
117 | HsPArrTy (HsType name) -- Elem. type of parallel array: [:t:]
120 [HsType name] -- Element types (length gives arity)
122 | HsOpTy (HsType name) (HsTyOp name) (HsType name)
124 | HsParTy (HsType name)
125 -- Parenthesis preserved for the precedence re-arrangement in RnTypes
126 -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
128 -- However, NB that toHsType doesn't add HsParTys (in an effort to keep
129 -- interface files smaller), so when printing a HsType we may need to
132 | HsNumTy Integer -- Generics only
134 -- these next two are only used in interfaces
135 | HsPredTy (HsPred name)
137 | HsKindSig (HsType name) -- (ty :: kind)
138 Kind -- A type with a kind signature
141 data HsTyOp name = HsArrow | HsTyOp name
142 -- Function arrows from *source* get read in as HsOpTy t1 HsArrow t2
143 -- But when we generate or parse interface files, we use HsFunTy.
144 -- This keeps interfaces a bit smaller, because there are a lot of arrows
146 -----------------------
147 hsUsOnce, hsUsMany :: HsType RdrName
148 hsUsOnce = HsTyVar (mkUnqual tvName FSLIT(".")) -- deep magic
149 hsUsMany = HsTyVar (mkUnqual tvName FSLIT("!")) -- deep magic
151 hsUsOnce_Name, hsUsMany_Name :: HsType Name
152 hsUsOnce_Name = HsTyVar usOnceTyConName
153 hsUsMany_Name = HsTyVar usManyTyConName
155 -----------------------
156 data HsTupCon = HsTupCon Boxity Arity
158 instance Eq HsTupCon where
159 (HsTupCon b1 a1) == (HsTupCon b2 a2) = b1==b2 && a1==a2
161 mkHsTupCon :: NameSpace -> Boxity -> [a] -> HsTupCon
162 mkHsTupCon space boxity args = HsTupCon boxity (length args)
164 hsTupParens :: HsTupCon -> SDoc -> SDoc
165 hsTupParens (HsTupCon b _) p = tupleParens b p
167 -----------------------
168 -- Combine adjacent for-alls.
169 -- The following awkward situation can happen otherwise:
170 -- f :: forall a. ((Num a) => Int)
171 -- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
172 -- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
173 -- but the export list abstracts f wrt [a]. Disaster.
175 -- A valid type must have one for-all at the top of the type, or of the fn arg types
177 mkHsForAllTy mtvs [] ty = mk_forall_ty mtvs ty
178 mkHsForAllTy mtvs ctxt ty = HsForAllTy mtvs ctxt ty
180 -- mk_forall_ty makes a pure for-all type (no context)
181 mk_forall_ty (Just []) ty = ty -- Explicit for-all with no tyvars
182 mk_forall_ty mtvs1 (HsParTy ty) = mk_forall_ty mtvs1 ty
183 mk_forall_ty mtvs1 (HsForAllTy mtvs2 ctxt ty) = mkHsForAllTy (mtvs1 `plus` mtvs2) ctxt ty
184 mk_forall_ty mtvs1 ty = HsForAllTy mtvs1 [] ty
186 mtvs1 `plus` Nothing = mtvs1
187 Nothing `plus` mtvs2 = mtvs2
188 (Just tvs1) `plus` (Just tvs2) = Just (tvs1 ++ tvs2)
190 mkHsDictTy cls tys = HsPredTy (HsClassP cls tys)
191 mkHsIParamTy v ty = HsPredTy (HsIParam v ty)
193 data HsTyVarBndr name
195 | IfaceTyVar name Kind
196 -- *** NOTA BENE *** A "monotype" in a pragma can have
197 -- for-alls in it, (mostly to do with dictionaries). These
198 -- must be explicitly Kinded.
200 hsTyVarName (UserTyVar n) = n
201 hsTyVarName (IfaceTyVar n _) = n
203 hsTyVarNames tvs = map hsTyVarName tvs
205 replaceTyVarName :: HsTyVarBndr name1 -> name2 -> HsTyVarBndr name2
206 replaceTyVarName (UserTyVar n) n' = UserTyVar n'
207 replaceTyVarName (IfaceTyVar n k) n' = IfaceTyVar n' k
215 -> ([HsTyVarBndr name], HsContext name, name, [HsType name])
216 -- Split up an instance decl type, returning the pieces
218 -- In interface files, the instance declaration head is created
219 -- by HsTypes.toHsType, which does not guarantee to produce a
220 -- HsForAllTy. For example, if we had the weird decl
221 -- instance Foo T => Foo [T]
222 -- then we'd get the instance type
224 -- So when colleting the instance context, to be on the safe side
225 -- we gather predicate arguments
227 -- For source code, the parser ensures the type will have the right shape.
228 -- (e.g. see ParseUtil.checkInstType)
230 splitHsInstDeclTy inst_ty
232 HsForAllTy (Just tvs) cxt1 tau
233 -> (tvs, cxt1++cxt2, cls, tys)
235 (cxt2, cls, tys) = split_tau tau
237 other -> ([], cxt2, cls, tys)
239 (cxt2, cls, tys) = split_tau inst_ty
242 split_tau (HsFunTy (HsPredTy p) ty) = (p:ps, cls, tys)
244 (ps, cls, tys) = split_tau ty
245 split_tau (HsPredTy (HsClassP cls tys)) = ([], cls,tys)
246 split_tau other = pprPanic "splitHsInstDeclTy" (ppr inst_ty)
250 %************************************************************************
252 \subsection{Pretty printing}
254 %************************************************************************
256 NB: these types get printed into interface files, so
257 don't change the printing format lightly
260 instance (Outputable name) => Outputable (HsType name) where
261 ppr ty = pprHsType ty
263 instance (Outputable name) => Outputable (HsTyOp name) where
264 ppr HsArrow = ftext FSLIT("->")
265 ppr (HsTyOp n) = ppr n
267 instance (Outputable name) => Outputable (HsTyVarBndr name) where
268 ppr (UserTyVar name) = ppr name
269 ppr (IfaceTyVar name kind) = pprHsTyVarBndr name kind
271 instance Outputable name => Outputable (HsPred name) where
272 ppr (HsClassP clas tys) = ppr clas <+> hsep (map pprParendHsType tys)
273 ppr (HsIParam n ty) = hsep [ppr n, dcolon, ppr ty]
275 pprHsTyVarBndr :: Outputable name => name -> Kind -> SDoc
276 pprHsTyVarBndr name kind | kind `eqKind` liftedTypeKind = ppr name
277 | otherwise = hsep [ppr name, dcolon, pprParendKind kind]
279 pprHsForAll [] [] = empty
281 -- This printer is used for both interface files and
282 -- printing user types in error messages; and alas the
283 -- two use slightly different syntax. Ah well.
284 = getPprStyle $ \ sty ->
285 if userStyle sty then
286 ptext SLIT("forall") <+> interppSP tvs <> dot <+>
287 -- **! ToDo: want to hide uvars from user, but not enough info
288 -- in a HsTyVarBndr name (see PprType). KSW 2000-10.
290 else -- Used in interfaces
291 ptext SLIT("__forall") <+> interppSP tvs <+>
292 ppr_hs_context cxt <+> ptext SLIT("=>")
294 pprHsContext :: (Outputable name) => HsContext name -> SDoc
295 pprHsContext [] = empty
296 pprHsContext cxt = ppr_hs_context cxt <+> ptext SLIT("=>")
298 ppr_hs_context [] = empty
299 ppr_hs_context cxt = parens (interpp'SP cxt)
303 pREC_TOP = (0 :: Int) -- type in ParseIface.y
304 pREC_FUN = (1 :: Int) -- btype in ParseIface.y
305 -- Used for LH arg of (->)
306 pREC_OP = (2 :: Int) -- Used for arg of any infix operator
307 -- (we don't keep their fixities around)
308 pREC_CON = (3 :: Int) -- Used for arg of type applicn:
309 -- always parenthesise unless atomic
311 maybeParen :: Int -- Precedence of context
312 -> Int -- Precedence of top-level operator
313 -> SDoc -> SDoc -- Wrap in parens if (ctxt >= op)
314 maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p
317 -- printing works more-or-less as for Types
319 pprHsType, pprParendHsType :: (Outputable name) => HsType name -> SDoc
321 pprHsType ty = ppr_mono_ty pREC_TOP (de_paren ty)
322 pprParendHsType ty = ppr_mono_ty pREC_CON ty
324 -- Remove outermost HsParTy parens before printing a type
325 de_paren (HsParTy ty) = de_paren ty
328 ppr_mono_ty ctxt_prec (HsForAllTy maybe_tvs ctxt ty)
329 = maybeParen ctxt_prec pREC_FUN $
330 sep [pp_header, pprHsType ty]
332 pp_header = case maybe_tvs of
333 Just tvs -> pprHsForAll tvs ctxt
334 Nothing -> pprHsContext ctxt
336 ppr_mono_ty ctxt_prec (HsTyVar name) = ppr name
337 ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2) = ppr_fun_ty ctxt_prec ty1 ty2
338 ppr_mono_ty ctxt_prec (HsTupleTy con tys) = hsTupParens con (interpp'SP tys)
339 ppr_mono_ty ctxt_prec (HsKindSig ty kind) = parens (ppr_mono_ty pREC_TOP ty <+> dcolon <+> pprKind kind)
340 ppr_mono_ty ctxt_prec (HsListTy ty) = brackets (ppr_mono_ty pREC_TOP ty)
341 ppr_mono_ty ctxt_prec (HsPArrTy ty) = pabrackets (ppr_mono_ty pREC_TOP ty)
342 ppr_mono_ty ctxt_prec (HsPredTy pred) = braces (ppr pred)
343 ppr_mono_ty ctxt_prec (HsNumTy n) = integer n -- generics only
345 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
346 = maybeParen ctxt_prec pREC_CON $
347 hsep [ppr_mono_ty pREC_FUN fun_ty, ppr_mono_ty pREC_CON arg_ty]
349 ppr_mono_ty ctxt_prec (HsOpTy ty1 HsArrow ty2)
350 = ppr_fun_ty ctxt_prec ty1 ty2
352 ppr_mono_ty ctxt_prec (HsOpTy ty1 op ty2)
353 = maybeParen ctxt_prec pREC_OP $
354 ppr_mono_ty pREC_OP ty1 <+> ppr op <+> ppr_mono_ty pREC_OP ty2
356 ppr_mono_ty ctxt_prec (HsParTy ty)
357 = parens (ppr_mono_ty pREC_TOP ty)
358 -- Put the parens in where the user did
359 -- But we still use the precedence stuff to add parens because
360 -- toHsType doesn't put in any HsParTys, so we may still need them
362 --------------------------
363 ppr_fun_ty ctxt_prec ty1 ty2
364 = let p1 = ppr_mono_ty pREC_FUN ty1
365 p2 = ppr_mono_ty pREC_TOP ty2
367 maybeParen ctxt_prec pREC_FUN $
368 sep [p1, ptext SLIT("->") <+> p2]
370 --------------------------
371 pabrackets p = ptext SLIT("[:") <> p <> ptext SLIT(":]")
375 %************************************************************************
377 \subsection{Converting from Type to HsType}
379 %************************************************************************
381 @toHsType@ converts from a Type to a HsType, making the latter look as
382 user-friendly as possible. Notably, it uses synonyms where possible, and
383 expresses overloaded functions using the '=>' context part of a HsForAllTy.
386 toHsTyVar :: TyVar -> HsTyVarBndr Name
387 toHsTyVar tv = IfaceTyVar (getName tv) (tyVarKind tv)
389 toHsTyVars tvs = map toHsTyVar tvs
391 toHsType :: Type -> HsType Name
392 -- This function knows the representation of types
393 toHsType (TyVarTy tv) = HsTyVar (getName tv)
394 toHsType (FunTy arg res) = HsFunTy (toHsType arg) (toHsType res)
395 toHsType (AppTy fun arg) = HsAppTy (toHsType fun) (toHsType arg)
397 toHsType (NoteTy (SynNote ty@(TyConApp tycon tyargs)) real_ty)
398 | isNewTyCon tycon = toHsType ty
399 | syn_matches = toHsType ty -- Use synonyms if possible!!
402 pprTrace "WARNING: synonym info lost in .hi file for " (ppr syn_ty) $
404 toHsType real_ty -- but drop it if not.
406 syn_matches = ty_from_syn `tcEqType` real_ty
407 (tyvars,syn_ty) = getSynTyConDefn tycon
408 ty_from_syn = substTyWith tyvars tyargs syn_ty
410 -- We only use the type synonym in the file if this doesn't cause
411 -- us to lose important information. This matters for usage
412 -- annotations. It's an issue if some of the args to the synonym
413 -- have arrows in them, or if the synonym's RHS has an arrow; for
414 -- example, with nofib/real/ebnf2ps/ in Parsers.using.
416 -- **! It would be nice if when this test fails we could still
417 -- write the synonym in as a Note, so we don't lose the info for
418 -- error messages, but it's too much work for right now.
421 toHsType (NoteTy _ ty) = toHsType ty
423 toHsType (SourceTy (NType tc tys)) = foldl HsAppTy (HsTyVar (getName tc)) (map toHsType tys)
424 toHsType (SourceTy pred) = HsPredTy (toHsPred pred)
426 toHsType ty@(TyConApp tc tys) -- Must be saturated because toHsType's arg is of kind *
427 | not saturated = generic_case
428 | isTupleTyCon tc = HsTupleTy (HsTupCon (tupleTyConBoxity tc) (tyConArity tc)) tys'
429 | tc `hasKey` listTyConKey = HsListTy (head tys')
430 | tc `hasKey` parrTyConKey = HsPArrTy (head tys')
431 | tc `hasKey` usOnceTyConKey = hsUsOnce_Name -- must print !, . unqualified
432 | tc `hasKey` usManyTyConKey = hsUsMany_Name -- must print !, . unqualified
433 | otherwise = generic_case
435 generic_case = foldl HsAppTy (HsTyVar (getName tc)) tys'
436 tys' = map toHsType tys
437 saturated = tys `lengthIs` tyConArity tc
439 toHsType ty@(ForAllTy _ _) = case tcSplitSigmaTy ty of
440 (tvs, preds, tau) -> HsForAllTy (Just (map toHsTyVar tvs))
444 toHsPred (ClassP cls tys) = HsClassP (getName cls) (map toHsType tys)
445 toHsPred (IParam n ty) = HsIParam n (toHsType ty)
447 toHsContext :: ThetaType -> HsContext Name
448 toHsContext theta = map toHsPred theta
450 toHsFDs :: [FunDep TyVar] -> [FunDep Name]
451 toHsFDs fds = [(map getName ns, map getName ms) | (ns,ms) <- fds]
455 %************************************************************************
457 \subsection{Comparison}
459 %************************************************************************
462 instance Ord a => Eq (HsType a) where
463 -- The Ord is needed because we keep a
464 -- finite map of variables to variables
465 (==) a b = eq_hsType emptyEqHsEnv a b
467 instance Ord a => Eq (HsPred a) where
468 (==) a b = eq_hsPred emptyEqHsEnv a b
470 eqWithHsTyVars :: Ord name =>
471 [HsTyVarBndr name] -> [HsTyVarBndr name]
472 -> (EqHsEnv name -> Bool) -> Bool
473 eqWithHsTyVars = eq_hsTyVars emptyEqHsEnv
477 type EqHsEnv n = FiniteMap n n
478 -- Tracks the mapping from L-variables to R-variables
480 eq_hsVar :: Ord n => EqHsEnv n -> n -> n -> Bool
481 eq_hsVar env n1 n2 = case lookupFM env n1 of
485 extendEqHsEnv env n1 n2
487 | otherwise = addToFM env n1 n2
489 emptyEqHsEnv :: EqHsEnv n
490 emptyEqHsEnv = emptyFM
493 We do define a specialised equality for these \tr{*Type} types; used
494 in checking interfaces.
498 eq_hsTyVars env [] [] k = k env
499 eq_hsTyVars env (tv1:tvs1) (tv2:tvs2) k = eq_hsTyVar env tv1 tv2 $ \ env ->
500 eq_hsTyVars env tvs1 tvs2 k
501 eq_hsTyVars env _ _ _ = False
503 eq_hsTyVar env (UserTyVar v1) (UserTyVar v2) k = k (extendEqHsEnv env v1 v2)
504 eq_hsTyVar env (IfaceTyVar v1 k1) (IfaceTyVar v2 k2) k = k1 `eqKind` k2 && k (extendEqHsEnv env v1 v2)
505 eq_hsTyVar env _ _ _ = False
507 eq_hsVars env [] [] k = k env
508 eq_hsVars env (v1:bs1) (v2:bs2) k = eq_hsVars (extendEqHsEnv env v1 v2) bs1 bs2 k
509 eq_hsVars env _ _ _ = False
514 eq_hsTypes env = eqListBy (eq_hsType env)
517 eq_hsType env (HsForAllTy tvs1 c1 t1) (HsForAllTy tvs2 c2 t2)
518 = eq_tvs tvs1 tvs2 $ \env ->
519 eq_hsContext env c1 c2 &&
522 eq_tvs Nothing (Just _) k = False
523 eq_tvs Nothing Nothing k = k env
524 eq_tvs (Just _) Nothing k = False
525 eq_tvs (Just tvs1) (Just tvs2) k = eq_hsTyVars env tvs1 tvs2 k
527 eq_hsType env (HsTyVar n1) (HsTyVar n2)
530 eq_hsType env (HsTupleTy c1 tys1) (HsTupleTy c2 tys2)
531 = (c1 == c2) && eq_hsTypes env tys1 tys2
533 eq_hsType env (HsListTy ty1) (HsListTy ty2)
534 = eq_hsType env ty1 ty2
536 eq_hsType env (HsKindSig ty1 k1) (HsKindSig ty2 k2)
537 = eq_hsType env ty1 ty2 && k1 `eqKind` k2
539 eq_hsType env (HsPArrTy ty1) (HsPArrTy ty2)
540 = eq_hsType env ty1 ty2
542 eq_hsType env (HsAppTy fun_ty1 arg_ty1) (HsAppTy fun_ty2 arg_ty2)
543 = eq_hsType env fun_ty1 fun_ty2 && eq_hsType env arg_ty1 arg_ty2
545 eq_hsType env (HsFunTy a1 b1) (HsFunTy a2 b2)
546 = eq_hsType env a1 a2 && eq_hsType env b1 b2
548 eq_hsType env (HsPredTy p1) (HsPredTy p2)
549 = eq_hsPred env p1 p2
551 eq_hsType env (HsOpTy lty1 op1 rty1) (HsOpTy lty2 op2 rty2)
552 = eq_hsOp env op1 op2 && eq_hsType env lty1 lty2 && eq_hsType env rty1 rty2
554 eq_hsType env ty1 ty2 = False
557 eq_hsOp env (HsTyOp n1) (HsTyOp n2) = eq_hsVar env n1 n2
558 eq_hsOp env HsArrow HsArrow = True
559 eq_hsOp env op1 op2 = False
562 eq_hsContext env a b = eqListBy (eq_hsPred env) a b
565 eq_hsPred env (HsClassP c1 tys1) (HsClassP c2 tys2)
566 = c1 == c2 && eq_hsTypes env tys1 tys2
567 eq_hsPred env (HsIParam n1 ty1) (HsIParam n2 ty2)
568 = n1 == n2 && eq_hsType env ty1 ty2
569 eq_hsPred env _ _ = False