2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Typechecking class declarations
9 module TcClassDcl ( tcClassSigs, tcClassDecl2,
10 findMethodBind, instantiateMethod, tcInstanceMethodBody,
12 tcAddDeclCtxt, badMethodErr, badATErr, omittedATWarn
15 #include "HsVersions.h"
19 import TcPat( addInlinePrags )
26 import BuildTyCl( TcMethInfo )
48 Every class implicitly declares a new data type, corresponding to dictionaries
49 of that class. So, for example:
51 class (D a) => C a where
53 op2 :: forall b. Ord b => a -> b -> b
55 would implicitly declare
57 data CDict a = CDict (D a)
59 (forall b. Ord b => a -> b -> b)
61 (We could use a record decl, but that means changing more of the existing apparatus.
64 For classes with just one superclass+method, we use a newtype decl instead:
67 op :: forallb. a -> b -> b
71 newtype CDict a = CDict (forall b. a -> b -> b)
73 Now DictTy in Type is just a form of type synomym:
74 DictTy c t = TyConTy CDict `AppTy` t
76 Death to "ExpandingDicts".
79 %************************************************************************
81 Type-checking the class op signatures
83 %************************************************************************
86 tcClassSigs :: Name -- Name of the class
89 -> TcM ([TcMethInfo], -- Exactly one for each method
90 NameEnv Type) -- Types of the generic-default methods
91 tcClassSigs clas sigs def_methods
92 = do { gen_dm_prs <- mapM (addLocM tc_gen_sig) gen_sigs
93 ; let gen_dm_env = mkNameEnv gen_dm_prs
95 ; op_info <- mapM (addLocM (tc_sig gen_dm_env)) vanilla_sigs
97 ; let op_names = mkNameSet [ n | (n,_,_) <- op_info ]
98 ; sequence_ [ failWithTc (badMethodErr clas n)
99 | n <- dm_bind_names, not (n `elemNameSet` op_names) ]
100 -- Value binding for non class-method (ie no TypeSig)
102 ; sequence_ [ failWithTc (badGenericMethod clas n)
103 | (n,_) <- gen_dm_prs, not (n `elem` dm_bind_names) ]
104 -- Generic signature without value binding
106 ; return (op_info, gen_dm_env) }
108 vanilla_sigs = [L loc (nm,ty) | L loc (TypeSig nm ty) <- sigs]
109 gen_sigs = [L loc (nm,ty) | L loc (GenericSig nm ty) <- sigs]
110 dm_bind_names :: [Name] -- These ones have a value binding in the class decl
111 dm_bind_names = [op | L _ (FunBind {fun_id = L _ op}) <- bagToList def_methods]
113 tc_sig genop_env (L _ op_name, op_hs_ty)
114 = do { op_ty <- tcHsKindedType op_hs_ty -- Class tyvars already in scope
115 ; let dm | op_name `elemNameEnv` genop_env = GenericDM
116 | op_name `elem` dm_bind_names = VanillaDM
118 ; return (op_name, dm, op_ty) }
120 tc_gen_sig (L _ op_name, gen_hs_ty)
121 = do { gen_op_ty <- tcHsKindedType gen_hs_ty
122 ; return (op_name, gen_op_ty) }
126 %************************************************************************
130 %************************************************************************
133 tcClassDecl2 :: LTyClDecl Name -- The class declaration
136 tcClassDecl2 (L loc (ClassDecl {tcdLName = class_name, tcdSigs = sigs,
137 tcdMeths = default_binds}))
138 = recoverM (return emptyLHsBinds) $
140 do { clas <- tcLookupLocatedClass class_name
142 -- We make a separate binding for each default method.
143 -- At one time I used a single AbsBinds for all of them, thus
144 -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
145 -- But that desugars into
146 -- ds = \d -> (..., ..., ...)
147 -- dm1 = \d -> case ds d of (a,b,c) -> a
148 -- And since ds is big, it doesn't get inlined, so we don't get good
149 -- default methods. Better to make separate AbsBinds for each
151 (tyvars, _, _, op_items) = classBigSig clas
152 prag_fn = mkPragFun sigs default_binds
153 sig_fn = mkSigFun sigs
154 clas_tyvars = tcSuperSkolTyVars tyvars
155 pred = mkClassPred clas (mkTyVarTys clas_tyvars)
156 ; this_dict <- newEvVar pred
158 ; traceTc "TIM2" (ppr sigs)
159 ; let tc_dm = tcDefMeth clas clas_tyvars
160 this_dict default_binds
163 ; dm_binds <- tcExtendTyVarEnv clas_tyvars $
166 ; return (unionManyBags dm_binds) }
168 tcClassDecl2 d = pprPanic "tcClassDecl2" (ppr d)
170 tcDefMeth :: Class -> [TyVar] -> EvVar -> LHsBinds Name
171 -> SigFun -> PragFun -> ClassOpItem
172 -> TcM (LHsBinds TcId)
173 -- Generate code for polymorphic default methods only (hence DefMeth)
174 -- (Generic default methods have turned into instance decls by now.)
175 -- This is incompatible with Hugs, which expects a polymorphic
176 -- default method for every class op, regardless of whether or not
177 -- the programmer supplied an explicit default decl for the class.
178 -- (If necessary we can fix that, but we don't have a convenient Id to hand.)
179 tcDefMeth clas tyvars this_dict binds_in sig_fn prag_fn (sel_id, dm_info)
181 NoDefMeth -> do { mapM_ (addLocM (badDmPrag sel_id)) prags
183 DefMeth dm_name -> tc_dm dm_name
184 GenDefMeth dm_name -> tc_dm dm_name
186 sel_name = idName sel_id
187 prags = prag_fn sel_name
188 dm_sig_fn _ = sig_fn sel_name
189 dm_bind = findMethodBind sel_name binds_in
190 `orElse` pprPanic "tcDefMeth" (ppr sel_id)
192 -- Eg. class C a where
193 -- op :: forall b. Eq b => a -> [b] -> a
195 -- generic gen_op :: D a => a -> a
196 -- The "local_dm_ty" is precisely the type in the above
197 -- type signatures, ie with no "forall a. C a =>" prefix
200 = do { dm_id <- tcLookupId dm_name
201 ; local_dm_name <- newLocalName sel_name
202 -- Base the local_dm_name on the selector name, because
203 -- type errors from tcInstanceMethodBody come from here
205 ; let local_dm_ty = instantiateMethod clas dm_id (mkTyVarTys tyvars)
206 local_dm_id = mkLocalId local_dm_name local_dm_ty
208 ; dm_id_w_inline <- addInlinePrags dm_id prags
209 ; spec_prags <- tcSpecPrags dm_id prags
211 ; warnTc (not (null spec_prags))
212 (ptext (sLit "Ignoring SPECIALISE pragmas on default method")
213 <+> quotes (ppr sel_name))
215 ; tc_bind <- tcInstanceMethodBody (ClsSkol clas) tyvars [this_dict]
216 dm_id_w_inline local_dm_id dm_sig_fn
217 IsDefaultMethod dm_bind
219 ; return (unitBag tc_bind) }
222 tcInstanceMethodBody :: SkolemInfo -> [TcTyVar] -> [EvVar]
224 -> SigFun -> TcSpecPrags -> LHsBind Name
226 tcInstanceMethodBody skol_info tyvars dfun_ev_vars
227 meth_id local_meth_id
230 = do { -- Typecheck the binding, first extending the envt
231 -- so that when tcInstSig looks up the local_meth_id to find
232 -- its signature, we'll find it in the environment
233 let lm_bind = L loc (bind { fun_id = L loc (idName local_meth_id) })
234 -- Substitute the local_meth_name for the binder
235 -- NB: the binding is always a FunBind
236 ; traceTc "TIM" (ppr local_meth_id $$ ppr (meth_sig_fn (idName local_meth_id)))
237 ; (ev_binds, (tc_bind, _))
238 <- checkConstraints skol_info tyvars dfun_ev_vars $
239 tcExtendIdEnv [local_meth_id] $
240 tcPolyBinds TopLevel meth_sig_fn no_prag_fn
241 NonRecursive NonRecursive
244 ; let full_bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
245 , abs_exports = [(tyvars, meth_id, local_meth_id, specs)]
246 , abs_ev_binds = ev_binds
247 , abs_binds = tc_bind }
249 ; return (L loc full_bind) }
251 no_prag_fn _ = [] -- No pragmas for local_meth_id;
252 -- they are all for meth_id
256 instantiateMethod :: Class -> Id -> [TcType] -> TcType
257 -- Take a class operation, say
258 -- op :: forall ab. C a => forall c. Ix c => (b,c) -> a
259 -- Instantiate it at [ty1,ty2]
260 -- Return the "local method type":
261 -- forall c. Ix x => (ty2,c) -> ty1
262 instantiateMethod clas sel_id inst_tys
263 = ASSERT( ok_first_pred ) local_meth_ty
265 (sel_tyvars,sel_rho) = tcSplitForAllTys (idType sel_id)
266 rho_ty = ASSERT( length sel_tyvars == length inst_tys )
267 substTyWith sel_tyvars inst_tys sel_rho
269 (first_pred, local_meth_ty) = tcSplitPredFunTy_maybe rho_ty
270 `orElse` pprPanic "tcInstanceMethod" (ppr sel_id)
272 ok_first_pred = case getClassPredTys_maybe first_pred of
273 Just (clas1, _tys) -> clas == clas1
275 -- The first predicate should be of form (C a b)
276 -- where C is the class in question
279 ---------------------------
280 findMethodBind :: Name -- Selector name
281 -> LHsBinds Name -- A group of bindings
282 -> Maybe (LHsBind Name) -- The binding
283 findMethodBind sel_name binds
284 = foldlBag mplus Nothing (mapBag f binds)
286 f bind@(L _ (FunBind { fun_id = L _ op_name }))
287 | op_name == sel_name
292 Note [Polymorphic methods]
293 ~~~~~~~~~~~~~~~~~~~~~~~~~~
296 op :: forall b. Ord b => a -> b -> b -> b
297 instance Foo c => Foo [c] where
300 When typechecking the binding 'op = e', we'll have a meth_id for op
302 op :: forall c. Foo c => forall b. Ord b => [c] -> b -> b -> b
304 So tcPolyBinds must be capable of dealing with nested polytypes;
305 and so it is. See TcBinds.tcMonoBinds (with type-sig case).
307 Note [Silly default-method bind]
308 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
309 When we pass the default method binding to the type checker, it must
312 otherwise the "$dm" stuff comes out error messages. But we want the
313 "$dm" to come out in the interface file. So we typecheck the former,
314 and wrap it in a let, thus
315 $dmop2 = let op2 = e in op2
316 This makes the error messages right.
319 %************************************************************************
321 Extracting generic instance declaration from class declarations
323 %************************************************************************
325 @getGenericInstances@ extracts the generic instance declarations from a class
326 declaration. For exmaple
331 op{ x+y } (Inl v) = ...
332 op{ x+y } (Inr v) = ...
333 op{ x*y } (v :*: w) = ...
336 gives rise to the instance declarations
338 instance C (x+y) where
342 instance C (x*y) where
349 mkGenericDefMethBind :: Class -> [Type] -> Id -> Name -> TcM (LHsBind Name)
350 mkGenericDefMethBind clas inst_tys sel_id dm_name
351 = -- A generic default method
352 -- If the method is defined generically, we only have to call the
354 do { dflags <- getDOpts
355 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Filling in method body"
356 (vcat [ppr clas <+> ppr inst_tys,
357 nest 2 (ppr sel_id <+> equals <+> ppr rhs)]))
359 ; return (noLoc $ mkFunBind (noLoc (idName sel_id))
360 [mkSimpleMatch [] rhs]) }
362 rhs = nlHsVar dm_name
365 %************************************************************************
369 %************************************************************************
372 tcAddDeclCtxt :: TyClDecl Name -> TcM a -> TcM a
373 tcAddDeclCtxt decl thing_inside
374 = addErrCtxt ctxt thing_inside
376 thing | isClassDecl decl = "class"
377 | isTypeDecl decl = "type synonym" ++ maybeInst
378 | isDataDecl decl = if tcdND decl == NewType
379 then "newtype" ++ maybeInst
380 else "data type" ++ maybeInst
381 | isFamilyDecl decl = "family"
382 | otherwise = panic "tcAddDeclCtxt/thing"
384 maybeInst | isFamInstDecl decl = " instance"
387 ctxt = hsep [ptext (sLit "In the"), text thing,
388 ptext (sLit "declaration for"), quotes (ppr (tcdName decl))]
390 badMethodErr :: Outputable a => a -> Name -> SDoc
392 = hsep [ptext (sLit "Class"), quotes (ppr clas),
393 ptext (sLit "does not have a method"), quotes (ppr op)]
395 badGenericMethod :: Outputable a => a -> Name -> SDoc
396 badGenericMethod clas op
397 = hsep [ptext (sLit "Class"), quotes (ppr clas),
398 ptext (sLit "has a generic-default signature without a binding"), quotes (ppr op)]
400 badATErr :: Class -> Name -> SDoc
402 = hsep [ptext (sLit "Class"), quotes (ppr clas),
403 ptext (sLit "does not have an associated type"), quotes (ppr at)]
405 omittedATWarn :: Name -> SDoc
407 = ptext (sLit "No explicit AT declaration for") <+> quotes (ppr at)
409 badGenericInstanceType :: LHsBinds Name -> SDoc
410 badGenericInstanceType binds
411 = vcat [ptext (sLit "Illegal type pattern in the generic bindings"),
414 missingGenericInstances :: [Name] -> SDoc
415 missingGenericInstances missing
416 = ptext (sLit "Missing type patterns for") <+> pprQuotedList missing
418 dupGenericInsts :: [(TyCon, InstInfo a)] -> SDoc
419 dupGenericInsts tc_inst_infos
420 = vcat [ptext (sLit "More than one type pattern for a single generic type constructor:"),
421 nest 2 (vcat (map ppr_inst_ty tc_inst_infos)),
422 ptext (sLit "All the type patterns for a generic type constructor must be identical")
425 ppr_inst_ty (_,inst) = ppr (simpleInstInfoTy inst)
427 badDmPrag :: Id -> Sig Name -> TcM ()
428 badDmPrag sel_id prag
429 = addErrTc (ptext (sLit "The") <+> hsSigDoc prag <+> ptext (sLit "for default method")
430 <+> quotes (ppr sel_id)
431 <+> ptext (sLit "lacks an accompanying binding"))