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 ( SYN_IE(RenamedMonoBinds), RenamedSig(..),
21 RenamedInstancePragmas(..) )
23 import TcMonad hiding ( rnMtoTcM )
24 import Inst ( SYN_IE(InstanceMapper) )
26 import Bag ( bagToList )
27 import Class ( GenClass, GenClassOp, SYN_IE(ClassInstEnv),
28 classBigSig, classOps, classOpLocalType,
31 import CoreSyn ( GenCoreExpr(..), mkValLam, mkTyApp )
32 import Id ( GenId, mkDictFunId, mkConstMethodId, mkSysLocal )
33 import MatchEnv ( nullMEnv, insertMEnv )
34 import Maybes ( MaybeErr(..), mkLookupFunDef )
35 import Name ( getSrcLoc, Name{--O only-} )
36 import PprType ( GenClass, GenType, GenTyVar )
38 import SpecEnv ( SpecEnv, nullSpecEnv, addOneToSpecEnv )
39 import SrcLoc ( SrcLoc )
40 import Type ( mkSigmaTy, mkForAllTys, mkDictTy, mkTyVarTys,
41 splitForAllTy, instantiateTy, matchTy, SYN_IE(ThetaType) )
42 import TyVar ( GenTyVar )
43 import Unique ( Unique )
44 import Util ( equivClasses, zipWithEqual, panic )
46 import IdInfo ( noIdInfo )
47 --import TcPragmas ( tcDictFunPragmas, tcGenPragmas )
50 instance c => k (t tvs) where b
56 [TyVar] -- Type variables, tvs
57 Type -- The type at which the class is being instantiated
58 ThetaType -- inst_decl_theta: the original context, c, from the
59 -- instance declaration. It constrains (some of)
61 ThetaType -- dfun_theta: the inst_decl_theta, plus one
62 -- element for each superclass; the "Mark
63 -- Jones optimisation"
65 [Id] -- Constant methods (either all or none)
66 RenamedMonoBinds -- Bindings, b
67 Bool -- True <=> local instance decl
68 Module -- Name of module where this instance defined
69 SrcLoc -- Source location assoc'd with this instance's defn
70 [RenamedSig] -- User pragmas recorded for generating specialised instances
73 %************************************************************************
75 \subsection{Creating instance related Ids}
77 %************************************************************************
80 mkInstanceRelatedIds :: Bool
83 -> RenamedInstancePragmas
89 -> TcM s (Id, ThetaType, [Id])
91 mkInstanceRelatedIds from_here src_loc inst_mod inst_pragmas
92 clas inst_tyvars inst_ty inst_decl_theta uprags
95 dfun_theta = case inst_decl_theta of
96 [] -> [] -- If inst_decl_theta is empty, then we don't
97 -- want to have any dict arguments, so that we can
98 -- expose the constant methods.
100 other -> inst_decl_theta ++ super_class_theta
101 -- Otherwise we pass the superclass dictionaries to
102 -- the dictionary function; the Mark Jones optimisation.
104 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_ty)
106 tcGetUnique `thenNF_Tc` \ dfun_uniq ->
107 fixTc ( \ rec_dfun_id ->
110 tcDictFunPragmas dfun_ty rec_dfun_id inst_pragmas
111 `thenNF_Tc` \ dfun_pragma_info ->
113 dfun_specenv = mkInstSpecEnv clas inst_ty inst_tyvars dfun_theta
114 dfun_id_info = dfun_pragma_info `addInfo` dfun_specenv
117 let dfun_id_info = noIdInfo in -- For now
119 returnTc (mkDictFunId dfun_uniq clas inst_ty dfun_ty from_here src_loc inst_mod dfun_id_info)
120 ) `thenTc` \ dfun_id ->
122 -- MAKE THE CONSTANT-METHOD IDS
123 -- if there are no type variables involved
124 (if (null inst_decl_theta)
126 mapTc mk_const_meth_id class_ops
129 ) `thenTc` \ const_meth_ids ->
131 returnTc (dfun_id, dfun_theta, const_meth_ids)
133 (class_tyvar, super_classes, _, class_ops, _, _) = classBigSig clas
134 tenv = [(class_tyvar, inst_ty)]
136 super_class_theta = super_classes `zip` repeat inst_ty
139 = tcGetUnique `thenNF_Tc` \ uniq ->
140 fixTc (\ rec_const_meth_id ->
143 -- Figure out the IdInfo from the pragmas
144 (case assocMaybe opname_prag_pairs (getName op) of
145 Nothing -> returnTc inline_info
146 Just prag -> tcGenPragmas (Just meth_ty) rec_const_meth_id prag
147 ) `thenNF_Tc` \ id_info ->
149 let id_info = noIdInfo -- For now
151 returnTc (mkConstMethodId uniq clas op inst_ty meth_ty
152 from_here src_loc inst_mod id_info)
155 op_ty = classOpLocalType op
156 meth_ty = mkForAllTys inst_tyvars (instantiateTy tenv op_ty)
158 inline_me = isIn "mkInstanceRelatedIds" op ops_to_inline
159 inline_info = if inline_me
160 then noIdInfo `addInfo_UF` (iWantToBeINLINEd UnfoldAlways)
163 opname_prag_pairs = case inst_pragmas of
164 ConstantInstancePragma _ name_prag_pairs -> name_prag_pairs
165 other_inst_pragmas -> []
167 ops_to_inline = [op | (InlineSig op _) <- uprags]
172 %************************************************************************
174 \subsection{Converting instance info into suitable InstEnvs}
176 %************************************************************************
179 buildInstanceEnvs :: Bag InstInfo
180 -> TcM s InstanceMapper
182 buildInstanceEnvs info
184 icmp :: InstInfo -> InstInfo -> TAG_
185 (InstInfo c1 _ _ _ _ _ _ _ _ _ _ _) `icmp` (InstInfo c2 _ _ _ _ _ _ _ _ _ _ _)
188 info_by_class = equivClasses icmp (bagToList info)
190 mapTc buildInstanceEnv info_by_class `thenTc` \ inst_env_entries ->
192 class_lookup_fn = mkLookupFunDef (==) inst_env_entries
193 (nullMEnv, \ o -> nullSpecEnv)
195 returnTc class_lookup_fn
199 buildInstanceEnv :: [InstInfo] -- Non-empty, and all for same class
200 -> TcM s (Class, (ClassInstEnv, (ClassOp -> SpecEnv)))
202 buildInstanceEnv inst_infos@((InstInfo clas _ _ _ _ _ _ _ _ _ _ _) : _)
203 = foldlTc addClassInstance
204 (nullMEnv, [(op, nullSpecEnv) | op <- classOps clas])
206 `thenTc` \ (class_inst_env, op_inst_envs) ->
207 returnTc (clas, (class_inst_env,
208 mkLookupFunDef (==) op_inst_envs
209 (panic "buildInstanceEnv")))
212 @addClassInstance@ adds the appropriate stuff to the @ClassInstEnv@
213 based on information from a single instance declaration. It complains
214 about any overlap with an existing instance.
218 :: (ClassInstEnv, [(ClassOp,SpecEnv)])
220 -> TcM s (ClassInstEnv, [(ClassOp,SpecEnv)])
223 (class_inst_env, op_spec_envs)
224 (InstInfo clas inst_tyvars inst_ty _ _
225 dfun_id const_meth_ids _ _ _ src_loc _)
228 -- We only add specialised/overlapped instances
229 -- if we are specialising the overloading
230 -- ToDo ... This causes getConstMethodId errors!
232 -- if not (is_plain_instance inst_ty) && not opt_SpecialiseOverloaded
234 -- -- Drop this specialised/overlapped instance
235 -- returnTc (class_inst_env, op_spec_envs)
238 -- Add the instance to the class's instance environment
239 case insertMEnv matchTy class_inst_env inst_ty dfun_id of {
240 Failed (ty', dfun_id') -> dupInstFailure clas (inst_ty, src_loc)
241 (ty', getSrcLoc dfun_id');
242 Succeeded class_inst_env' ->
244 -- If there are any constant methods, then add them to
245 -- the SpecEnv of each class op (ie selector)
247 -- Example. class Foo a where { op :: Baz b => a -> b; ... }
248 -- instance Foo (p,q) where { op (x,y) = ... ; ... }
250 -- The class decl means that
251 -- op :: forall a. Foo a => forall b. Baz b => a -> b
253 -- The constant method from the instance decl will be:
254 -- op_Pair :: forall p q b. Baz b => (p,q) -> b
256 -- What we put in op's SpecEnv is
257 -- (p,q) |--> (\d::Foo (p,q) -> op_Pair p q)
259 -- Here, [p,q] are the inst_tyvars, and d is a dict whose only
260 -- purpose is to cancel with the dict to which op is applied.
262 -- NOTE THAT this correctly deals with the case where there are
263 -- constant methods even though there are type variables in the
264 -- instance declaration.
266 tcGetUnique `thenNF_Tc` \ uniq ->
268 dict = mkSysLocal SLIT("dict_tpl") uniq (mkDictTy clas inst_ty) src_loc
269 -- Slightly disgusting, but it's only a placeholder for
270 -- a dictionary to be chucked away.
272 op_spec_envs' | null const_meth_ids = op_spec_envs
273 | otherwise = zipWithEqual "add_const_meth" add_const_meth op_spec_envs const_meth_ids
275 add_const_meth (op,spec_env) meth_id
276 = (op, case addOneToSpecEnv spec_env [inst_ty] rhs of
277 Failed (tys', rhs') -> panic "TcInstDecls:add_const_meth"
278 Succeeded spec_env' -> spec_env' )
280 rhs = mkValLam [dict] (mkTyApp (Var meth_id) (mkTyVarTys inst_tyvars))
282 returnTc (class_inst_env', op_spec_envs')
287 dupInstFailure clas info1@(ty1, locn1) info2@(ty2, locn2)
288 -- Overlapping/duplicate instances for given class; msg could be more glamourous
289 = tcAddErrCtxt ctxt $
290 failTc (\sty -> ppStr "Duplicate or overlapping instance declarations")
292 ctxt sty = ppHang (ppSep [ppBesides[ppStr "Class `", ppr sty clas, ppStr "'"],
293 ppBesides[ppStr "type `", ppr sty ty1, ppStr "'"]])
294 4 (ppSep [ppBesides [ppStr "at ", ppr sty locn1],
295 ppBesides [ppStr "and ", ppr sty locn2]])