2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[TcInstUtil]{Utilities for typechecking instance declarations}
6 The bits common to TcInstDcls and TcDeriv.
9 #include "HsVersions.h"
19 import HsSyn ( MonoBinds, Fake, InPat, Sig )
20 import RnHsSyn ( RenamedMonoBinds(..), RenamedSig(..),
21 RenamedInstancePragmas(..) )
24 import Inst ( InstanceMapper(..) )
26 import Bag ( bagToList )
27 import Class ( GenClass, GenClassOp, ClassInstEnv(..),
28 getClassBigSig, getClassOps, getClassOpLocalType )
29 import CoreSyn ( GenCoreExpr(..), mkValLam, mkTyApp )
30 import Id ( GenId, mkDictFunId, mkConstMethodId, mkSysLocal )
31 import MatchEnv ( nullMEnv, insertMEnv )
32 import Maybes ( MaybeErr(..), mkLookupFunDef )
33 import PprType ( GenClass, GenType, GenTyVar )
35 import SpecEnv ( SpecEnv(..), nullSpecEnv, addOneToSpecEnv )
36 import SrcLoc ( SrcLoc )
37 import Type ( mkSigmaTy, mkForAllTys, mkDictTy, mkTyVarTy,
38 splitForAllTy, instantiateTy, matchTy, ThetaType(..) )
39 import TyVar ( GenTyVar )
40 import Unique ( Unique )
41 import Util ( equivClasses, zipWithEqual, panic )
44 import IdInfo ( noIdInfo )
45 --import TcPragmas ( tcDictFunPragmas, tcGenPragmas )
48 instance c => k (t tvs) where b
54 [TyVar] -- Type variables, tvs
55 Type -- The type at which the class is being instantiated
56 ThetaType -- inst_decl_theta: the original context, c, from the
57 -- instance declaration. It constrains (some of)
59 ThetaType -- dfun_theta: the inst_decl_theta, plus one
60 -- element for each superclass; the "Mark
61 -- Jones optimisation"
63 [Id] -- Constant methods (either all or none)
64 RenamedMonoBinds -- Bindings, b
65 Bool -- True <=> local instance decl
66 FAST_STRING -- Name of module where this instance was
68 SrcLoc -- Source location assoc'd with this instance's defn
69 [RenamedSig] -- User pragmas recorded for generating specialised instances
72 %************************************************************************
74 \subsection{Creating instance related Ids}
76 %************************************************************************
79 mkInstanceRelatedIds :: Bool -> FAST_STRING
80 -> RenamedInstancePragmas
86 -> TcM s (Id, ThetaType, [Id])
88 mkInstanceRelatedIds from_here inst_mod inst_pragmas
89 clas inst_tyvars inst_ty inst_decl_theta uprags
92 dfun_theta = case inst_decl_theta of
93 [] -> [] -- If inst_decl_theta is empty, then we don't
94 -- want to have any dict arguments, so that we can
95 -- expose the constant methods.
97 other -> inst_decl_theta ++ super_class_theta
98 -- Otherwise we pass the superclass dictionaries to
99 -- the dictionary function; the Mark Jones optimisation.
101 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_ty)
103 tcGetUnique `thenNF_Tc` \ dfun_uniq ->
104 fixTc ( \ rec_dfun_id ->
107 tcDictFunPragmas dfun_ty rec_dfun_id inst_pragmas
108 `thenNF_Tc` \ dfun_pragma_info ->
110 dfun_specenv = mkInstSpecEnv clas inst_ty inst_tyvars dfun_theta
111 dfun_id_info = dfun_pragma_info `addInfo` dfun_specenv
114 let dfun_id_info = noIdInfo in -- For now
116 returnTc (mkDictFunId dfun_uniq clas inst_ty dfun_ty from_here inst_mod dfun_id_info)
117 ) `thenTc` \ dfun_id ->
119 -- MAKE THE CONSTANT-METHOD IDS
120 -- if there are no type variables involved
121 (if not (null inst_decl_theta)
125 mapTc mk_const_meth_id class_ops
126 ) `thenTc` \ const_meth_ids ->
128 returnTc (dfun_id, dfun_theta, const_meth_ids)
130 (class_tyvar, super_classes, _, class_ops, _, _) = getClassBigSig clas
131 tenv = [(class_tyvar, inst_ty)]
133 super_class_theta = super_classes `zip` (repeat inst_ty)
136 = tcGetUnique `thenNF_Tc` \ uniq ->
137 fixTc (\ rec_const_meth_id ->
140 -- Figure out the IdInfo from the pragmas
141 (case assocMaybe opname_prag_pairs (getName op) of
142 Nothing -> returnTc inline_info
143 Just prag -> tcGenPragmas (Just meth_ty) rec_const_meth_id prag
144 ) `thenNF_Tc` \ id_info ->
146 let id_info = noIdInfo -- For now
148 returnTc (mkConstMethodId uniq clas op inst_ty meth_ty
149 from_here inst_mod id_info)
152 op_ty = getClassOpLocalType op
153 meth_ty = mkForAllTys inst_tyvars (instantiateTy tenv op_ty)
155 inline_me = isIn "mkInstanceRelatedIds" op ops_to_inline
156 inline_info = if inline_me
157 then noIdInfo `addInfo_UF` (iWantToBeINLINEd UnfoldAlways)
160 opname_prag_pairs = case inst_pragmas of
161 ConstantInstancePragma _ name_prag_pairs -> name_prag_pairs
162 other_inst_pragmas -> []
164 ops_to_inline = [op | (InlineSig op _) <- uprags]
169 %************************************************************************
171 \subsection{Converting instance info into suitable InstEnvs}
173 %************************************************************************
176 buildInstanceEnvs :: Bag InstInfo
177 -> TcM s InstanceMapper
179 buildInstanceEnvs info
181 icmp :: InstInfo -> InstInfo -> TAG_
182 (InstInfo c1 _ _ _ _ _ _ _ _ _ _ _) `icmp` (InstInfo c2 _ _ _ _ _ _ _ _ _ _ _)
185 info_by_class = equivClasses icmp (bagToList info)
187 mapTc buildInstanceEnv info_by_class `thenTc` \ inst_env_entries ->
189 class_lookup_fn = mkLookupFunDef (==) inst_env_entries
190 (nullMEnv, \ o -> nullSpecEnv)
192 returnTc class_lookup_fn
196 buildInstanceEnv :: [InstInfo] -- Non-empty, and all for same class
197 -> TcM s (Class, (ClassInstEnv, (ClassOp -> SpecEnv)))
199 buildInstanceEnv inst_infos@((InstInfo clas _ _ _ _ _ _ _ _ _ _ _) : _)
200 = foldlTc addClassInstance
201 (nullMEnv, [(op, nullSpecEnv) | op <- getClassOps clas])
203 `thenTc` \ (class_inst_env, op_inst_envs) ->
204 returnTc (clas, (class_inst_env,
205 mkLookupFunDef (==) op_inst_envs
206 (panic "buildInstanceEnv")))
209 @addClassInstance@ adds the appropriate stuff to the @ClassInstEnv@
210 based on information from a single instance declaration. It complains
211 about any overlap with an existing instance.
215 :: (ClassInstEnv, [(ClassOp,SpecEnv)])
217 -> TcM s (ClassInstEnv, [(ClassOp,SpecEnv)])
220 (class_inst_env, op_spec_envs)
221 (InstInfo clas inst_tyvars inst_ty inst_decl_theta dfun_theta
222 dfun_id const_meth_ids _ _ _ src_loc _)
225 -- We only add specialised/overlapped instances
226 -- if we are specialising the overloading
227 -- ToDo ... This causes getConstMethodId errors!
229 -- if not (is_plain_instance inst_ty) && not opt_SpecialiseOverloaded
231 -- -- Drop this specialised/overlapped instance
232 -- returnTc (class_inst_env, op_spec_envs)
235 -- Add the instance to the class's instance environment
236 case insertMEnv matchTy class_inst_env inst_ty dfun_id of {
237 Failed (ty', dfun_id') -> failTc (dupInstErr clas (inst_ty, src_loc)
238 (ty', getSrcLoc dfun_id'));
239 Succeeded class_inst_env' ->
241 -- If there are any constant methods, then add them to
242 -- the SpecEnv of each class op (ie selector)
244 -- Example. class Foo a where { op :: Baz b => a -> b }
245 -- instance Foo (p,q) where { op (x,y) = ... }
247 -- The constant method from the instance decl will be:
248 -- op_Pair :: forall p q b. Baz b => (p,q) -> b
250 -- What we put in op's SpecEnv is
251 -- (p,q) b |--> (\d::Foo (p,q) -> op_Pair p q b)
253 -- Here, [p,q] are the inst_tyvars, and d is a dict whose only
254 -- purpose is to cancel with the dict to which op is applied.
256 -- NOTE THAT this correctly deals with the case where there are
257 -- constant methods even though there are type variables in the
258 -- instance declaration.
260 tcGetUnique `thenNF_Tc` \ uniq ->
262 dict = mkSysLocal SLIT("dict_tpl") uniq (mkDictTy clas inst_ty) src_loc
263 -- Slightly disgusting, but it's only a placeholder for
264 -- a dictionary to be chucked away.
266 op_spec_envs' | null const_meth_ids = op_spec_envs
267 | otherwise = zipWithEqual add_const_meth op_spec_envs const_meth_ids
269 add_const_meth (op,spec_env) meth_id
270 = (op, case addOneToSpecEnv spec_env (inst_ty : local_tyvar_tys) rhs of
271 Failed (tys', rhs') -> panic "TcInstDecls:add_const_meth"
272 Succeeded spec_env' -> spec_env' )
274 (local_tyvars, _) = splitForAllTy (getClassOpLocalType op)
275 local_tyvar_tys = map mkTyVarTy local_tyvars
276 rhs = mkValLam [dict] (mkTyApp (mkTyApp (Var meth_id)
277 (map mkTyVarTy inst_tyvars))
280 returnTc (class_inst_env', op_spec_envs')
285 dupInstErr clas info1@(ty1, locn1) info2@(ty2, locn2) sty
286 -- Overlapping/duplicate instances for given class; msg could be more glamourous
287 = ppHang (ppBesides [ppStr "Duplicate/overlapping instances: class `", ppr sty clas, ppStr "'"])
288 4 (showOverlap sty info1 info2)
290 showOverlap sty (ty1,loc1) (ty2,loc2)
291 = ppSep [ppBesides [ppStr "type `", ppr sty ty1, ppStr "'"],
292 ppBesides [ppStr "at ", ppr sty loc1],
293 ppBesides [ppStr "and ", ppr sty loc2]]