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 TcEnv ( tcLookupGlobalValueMaybe )
25 import Inst ( SYN_IE(InstanceMapper) )
27 import Bag ( bagToList )
28 import Class ( GenClass, GenClassOp, SYN_IE(ClassInstEnv),
29 classBigSig, classOps, classOpLocalType,
32 import CoreSyn ( GenCoreExpr(..), mkValLam, mkTyApp )
33 import Id ( GenId, mkDictFunId, mkConstMethodId, mkSysLocal, replaceIdInfo, getIdInfo )
34 import MatchEnv ( nullMEnv, insertMEnv )
35 import Maybes ( MaybeErr(..), mkLookupFunDef )
36 import Name ( getSrcLoc, Name{--O only-} )
37 import PprType ( GenClass, GenType, GenTyVar )
39 import SpecEnv ( SpecEnv, nullSpecEnv, addOneToSpecEnv )
40 import SrcLoc ( SrcLoc )
41 import Type ( mkSigmaTy, mkForAllTys, mkDictTy, mkTyVarTys,
42 splitForAllTy, instantiateTy, matchTy, SYN_IE(ThetaType) )
43 import TyVar ( GenTyVar )
44 import Unique ( Unique )
45 import Util ( equivClasses, zipWithEqual, panic{-, pprTrace-} )
48 import IdInfo ( noIdInfo )
49 --import TcPragmas ( tcDictFunPragmas, tcGenPragmas )
52 instance c => k (t tvs) where b
58 [TyVar] -- Type variables, tvs
59 Type -- The type at which the class is being instantiated
60 ThetaType -- inst_decl_theta: the original context, c, from the
61 -- instance declaration. It constrains (some of)
63 ThetaType -- dfun_theta: the inst_decl_theta, plus one
64 -- element for each superclass; the "Mark
65 -- Jones optimisation"
67 RenamedMonoBinds -- Bindings, b
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 :: Name -- Name to use for the dict fun;
84 -> NF_TcM s (Id, ThetaType)
86 mkInstanceRelatedIds dfun_name clas inst_tyvars inst_ty inst_decl_theta
87 = tcLookupGlobalValueMaybe dfun_name `thenNF_Tc` \ maybe_id ->
89 -- Extract the dfun's IdInfo from the interface file,
90 -- provided it's imported.
91 -- We have to be lazy here; people look at the dfun Id itself
92 dfun_info = case maybe_id of
94 Just imported_dfun_id -> getIdInfo imported_dfun_id
96 returnNF_Tc (new_dfun_id `replaceIdInfo` dfun_info, dfun_theta)
99 (_, super_classes, _, _, _, _) = classBigSig clas
100 super_class_theta = super_classes `zip` repeat inst_ty
102 dfun_theta = case inst_decl_theta of
103 [] -> [] -- If inst_decl_theta is empty, then we don't
104 -- want to have any dict arguments, so that we can
105 -- expose the constant methods.
107 other -> inst_decl_theta ++ super_class_theta
108 -- Otherwise we pass the superclass dictionaries to
109 -- the dictionary function; the Mark Jones optimisation.
111 dfun_ty = mkSigmaTy inst_tyvars dfun_theta (mkDictTy clas inst_ty)
113 new_dfun_id = mkDictFunId dfun_name dfun_ty clas inst_ty
117 %************************************************************************
119 \subsection{Converting instance info into suitable InstEnvs}
121 %************************************************************************
124 buildInstanceEnvs :: Bag InstInfo
125 -> TcM s InstanceMapper
127 buildInstanceEnvs info
129 icmp :: InstInfo -> InstInfo -> TAG_
130 (InstInfo c1 _ _ _ _ _ _ _ _) `icmp` (InstInfo c2 _ _ _ _ _ _ _ _)
133 info_by_class = equivClasses icmp (bagToList info)
135 mapTc buildInstanceEnv info_by_class `thenTc` \ inst_env_entries ->
137 class_lookup_fn = mkLookupFunDef (==) inst_env_entries
138 (nullMEnv, \ o -> nullSpecEnv)
140 returnTc class_lookup_fn
144 buildInstanceEnv :: [InstInfo] -- Non-empty, and all for same class
145 -> TcM s (Class, (ClassInstEnv, (ClassOp -> SpecEnv)))
147 buildInstanceEnv inst_infos@((InstInfo clas _ _ _ _ _ _ _ _) : _)
148 = foldlTc addClassInstance
149 (nullMEnv, [(op, nullSpecEnv) | op <- classOps clas])
151 `thenTc` \ (class_inst_env, op_inst_envs) ->
152 returnTc (clas, (class_inst_env,
153 mkLookupFunDef (==) op_inst_envs
154 (panic "buildInstanceEnv")))
157 @addClassInstance@ adds the appropriate stuff to the @ClassInstEnv@
158 based on information from a single instance declaration. It complains
159 about any overlap with an existing instance.
163 :: (ClassInstEnv, [(ClassOp,SpecEnv)])
165 -> TcM s (ClassInstEnv, [(ClassOp,SpecEnv)])
168 input_stuff@(class_inst_env, op_spec_envs)
169 (InstInfo clas inst_tyvars inst_ty _ _
173 -- We only add specialised/overlapped instances
174 -- if we are specialising the overloading
175 -- ToDo ... This causes getConstMethodId errors!
177 -- if not (is_plain_instance inst_ty) && not opt_SpecialiseOverloaded
179 -- -- Drop this specialised/overlapped instance
180 -- returnTc (class_inst_env, op_spec_envs)
183 -- Add the instance to the class's instance environment
184 case insertMEnv matchTy class_inst_env inst_ty dfun_id of {
185 Failed (ty', dfun_id') -> recoverTc (returnTc input_stuff) $
186 dupInstFailure clas (inst_ty, src_loc)
187 (ty', getSrcLoc dfun_id');
188 Succeeded class_inst_env' ->
190 returnTc (class_inst_env', op_spec_envs)
192 {- OLD STUFF FOR CONSTANT METHODS
194 -- If there are any constant methods, then add them to
195 -- the SpecEnv of each class op (ie selector)
197 -- Example. class Foo a where { op :: Baz b => a -> b; ... }
198 -- instance Foo (p,q) where { op (x,y) = ... ; ... }
200 -- The class decl means that
201 -- op :: forall a. Foo a => forall b. Baz b => a -> b
203 -- The constant method from the instance decl will be:
204 -- op_Pair :: forall p q b. Baz b => (p,q) -> b
206 -- What we put in op's SpecEnv is
207 -- (p,q) |--> (\d::Foo (p,q) -> op_Pair p q)
209 -- Here, [p,q] are the inst_tyvars, and d is a dict whose only
210 -- purpose is to cancel with the dict to which op is applied.
212 -- NOTE THAT this correctly deals with the case where there are
213 -- constant methods even though there are type variables in the
214 -- instance declaration.
216 tcGetUnique `thenNF_Tc` \ uniq ->
218 dict = mkSysLocal SLIT("dict_tpl") uniq (mkDictTy clas inst_ty) src_loc
219 -- Slightly disgusting, but it's only a placeholder for
220 -- a dictionary to be chucked away.
222 op_spec_envs' | null const_meth_ids = op_spec_envs
223 | otherwise = zipWithEqual "add_const_meth" add_const_meth op_spec_envs const_meth_ids
225 add_const_meth (op,spec_env) meth_id
226 = (op, case addOneToSpecEnv spec_env [inst_ty] rhs of
227 Failed (tys', rhs') -> panic "TcInstDecls:add_const_meth"
228 Succeeded spec_env' -> spec_env' )
230 rhs = mkValLam [dict] (mkTyApp (Var meth_id) (mkTyVarTys inst_tyvars))
232 returnTc (class_inst_env', op_spec_envs')
239 dupInstFailure clas info1@(ty1, locn1) info2@(ty2, locn2)
240 -- Overlapping/duplicate instances for given class; msg could be more glamourous
241 = tcAddErrCtxt ctxt $
242 failTc (\sty -> ppStr "Duplicate or overlapping instance declarations")
244 ctxt sty = ppHang (ppSep [ppBesides[ppStr "Class `", ppr sty clas, ppStr "'"],
245 ppBesides[ppStr "type `", ppr sty ty1, ppStr "'"]])
246 4 (ppSep [ppBesides [ppStr "at ", ppr sty locn1],
247 ppBesides [ppStr "and ", ppr sty locn2]])