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,
11 mkGenericDefMethBind, getGenericInstances,
12 tcAddDeclCtxt, badMethodErr, badATErr, omittedATWarn
15 #include "HsVersions.h"
28 import BuildTyCl( TcMethInfo )
56 Every class implicitly declares a new data type, corresponding to dictionaries
57 of that class. So, for example:
59 class (D a) => C a where
61 op2 :: forall b. Ord b => a -> b -> b
63 would implicitly declare
65 data CDict a = CDict (D a)
67 (forall b. Ord b => a -> b -> b)
69 (We could use a record decl, but that means changing more of the existing apparatus.
72 For classes with just one superclass+method, we use a newtype decl instead:
75 op :: forallb. a -> b -> b
79 newtype CDict a = CDict (forall b. a -> b -> b)
81 Now DictTy in Type is just a form of type synomym:
82 DictTy c t = TyConTy CDict `AppTy` t
84 Death to "ExpandingDicts".
87 %************************************************************************
89 Type-checking the class op signatures
91 %************************************************************************
94 tcClassSigs :: Name -- Name of the class
97 -> TcM [TcMethInfo] -- One for each method
99 tcClassSigs clas sigs def_methods
100 = do { -- Check that all def_methods are in the class
101 ; op_info <- mapM (addLocM tc_sig) [sig | sig@(L _ (TypeSig _ _)) <- sigs]
102 ; let op_names = [ n | (n,_,_) <- op_info ]
104 ; sequence_ [ failWithTc (badMethodErr clas n)
105 | n <- dm_bind_names, not (n `elem` op_names) ]
106 -- Value binding for non class-method (ie no TypeSig)
108 ; sequence_ [ failWithTc (badGenericMethod clas n)
109 | n <- genop_names, not (n `elem` dm_bind_names) ]
110 -- Generic signature without value binding
114 dm_bind_names :: [Name] -- These ones have a value binding in the class decl
115 dm_bind_names = [op | L _ (FunBind {fun_id = L _ op}) <- bagToList def_methods]
117 genop_names :: [Name] -- These ones have a generic signature
118 genop_names = [n | L _ (GenericSig (L _ n) _) <- sigs]
120 tc_sig (TypeSig (L _ op_name) op_hs_ty)
121 = do { op_ty <- tcHsKindedType op_hs_ty -- Class tyvars already in scope
122 ; let dm | op_name `elem` genop_names = GenericDM
123 | op_name `elem` dm_bind_names = VanillaDM
125 ; return (op_name, dm, op_ty) }
126 tc_sig sig = pprPanic "tc_cls_sig" (ppr sig)
130 %************************************************************************
134 %************************************************************************
137 tcClassDecl2 :: LTyClDecl Name -- The class declaration
140 tcClassDecl2 (L loc (ClassDecl {tcdLName = class_name, tcdSigs = sigs,
141 tcdMeths = default_binds}))
142 = recoverM (return emptyLHsBinds) $
144 do { clas <- tcLookupLocatedClass class_name
146 -- We make a separate binding for each default method.
147 -- At one time I used a single AbsBinds for all of them, thus
148 -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
149 -- But that desugars into
150 -- ds = \d -> (..., ..., ...)
151 -- dm1 = \d -> case ds d of (a,b,c) -> a
152 -- And since ds is big, it doesn't get inlined, so we don't get good
153 -- default methods. Better to make separate AbsBinds for each
155 (tyvars, _, _, op_items) = classBigSig clas
156 prag_fn = mkPragFun sigs default_binds
157 sig_fn = mkSigFun sigs
158 clas_tyvars = tcSuperSkolTyVars tyvars
159 pred = mkClassPred clas (mkTyVarTys clas_tyvars)
160 ; this_dict <- newEvVar pred
162 ; traceTc "TIM2" (ppr sigs)
163 ; let tc_dm = tcDefMeth clas clas_tyvars
164 this_dict default_binds sigs
167 ; dm_binds <- tcExtendTyVarEnv clas_tyvars $
170 ; return (unionManyBags dm_binds) }
172 tcClassDecl2 d = pprPanic "tcClassDecl2" (ppr d)
174 tcDefMeth :: Class -> [TyVar] -> EvVar -> LHsBinds Name -> [LSig Name]
175 -> SigFun -> PragFun -> ClassOpItem
176 -> TcM (LHsBinds TcId)
177 -- Generate code for polymorphic default methods only (hence DefMeth)
178 -- (Generic default methods have turned into instance decls by now.)
179 -- This is incompatible with Hugs, which expects a polymorphic
180 -- default method for every class op, regardless of whether or not
181 -- the programmer supplied an explicit default decl for the class.
182 -- (If necessary we can fix that, but we don't have a convenient Id to hand.)
183 tcDefMeth _ tyvars _ binds_in sigs sig_fn prag_fn (sel_id, dm_info)
184 | NoDefMeth <- dm_info = return emptyBag
186 = do { (dm_id, tvs, sig_loc) <- tc_dm_id dm_info
187 ; let L loc meth_bind = findMethodBind sel_name binds_in
188 `orElse` pprPanic "tcDefMeth" (ppr sel_id)
189 dm_bind = L loc (meth_bind { fun_id = L loc (idName dm_id) })
190 -- Substitute the meth_name for the binder
191 -- NB: the binding is always a FunBind
193 dm_sig_fn _ = Just (clas_tv_names ++ tvs, sig_loc)
194 dm_prag_fn _ = prag_fn sel_name
196 ; (binds,_) <- tcExtendIdEnv [dm_id] $
197 tcPolyBinds TopLevel dm_sig_fn dm_prag_fn
198 NonRecursive NonRecursive
202 sel_name = idName sel_id
203 clas_tv_names = map getName tyvars
205 -- Find the 'generic op :: ty' signature among the sigs
206 -- If dm_info is GenDefMeth, the corresponding signature
207 -- should jolly well exist! Hence the panic
208 genop_lhs_ty = case [lty | L _ (GenericSig (L _ n) lty) <- sigs
211 _ -> pprPanic "tcDefMeth" (ppr sel_name $$ ppr sigs)
213 tc_dm_id :: DefMeth -> TcM (Id, [Name], SrcSpan)
214 -- Make a default-method Id of the appropriate type
215 -- That may entail getting the generic-default signature
216 -- from the type signatures.
217 -- Also return the in-scope tyvars for the default method, and their binding site
218 tc_dm_id NoDefMeth = panic "tc_dm_id"
219 tc_dm_id (DefMeth dm_name)
220 | Just (tvs, loc) <- sig_fn sel_name
221 = return (mkDefaultMethodId sel_id dm_name, tvs, loc)
223 = pprPanic "No sig for" (ppr sel_name)
224 tc_dm_id (GenDefMeth dm_name)
226 do { tau <- tcHsKindedType genop_lhs_ty
227 ; checkValidType (FunSigCtxt sel_name) tau
228 ; return ( mkExportedLocalId dm_name (mkForAllTys tyvars tau)
229 , hsExplicitTvs genop_lhs_ty, loc ) }
231 loc = getLoc genop_lhs_ty
234 tcInstanceMethodBody :: SkolemInfo -> [TcTyVar] -> [EvVar]
236 -> SigFun -> TcSpecPrags -> LHsBind Name
238 tcInstanceMethodBody skol_info tyvars dfun_ev_vars
239 meth_id local_meth_id
242 = do { -- Typecheck the binding, first extending the envt
243 -- so that when tcInstSig looks up the local_meth_id to find
244 -- its signature, we'll find it in the environment
245 let lm_bind = L loc (bind { fun_id = L loc (idName local_meth_id) })
246 -- Substitute the local_meth_name for the binder
247 -- NB: the binding is always a FunBind
248 ; traceTc "TIM" (ppr local_meth_id $$ ppr (meth_sig_fn (idName local_meth_id)))
249 ; (ev_binds, (tc_bind, _))
250 <- checkConstraints skol_info tyvars dfun_ev_vars $
251 tcExtendIdEnv [local_meth_id] $
252 tcPolyBinds TopLevel meth_sig_fn no_prag_fn
253 NonRecursive NonRecursive
256 ; let full_bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars
257 , abs_exports = [(tyvars, meth_id, local_meth_id, specs)]
258 , abs_ev_binds = ev_binds
259 , abs_binds = tc_bind }
261 ; return (L loc full_bind) }
263 no_prag_fn _ = [] -- No pragmas for local_meth_id;
264 -- they are all for meth_id
268 instantiateMethod :: Class -> Id -> [TcType] -> TcType
269 -- Take a class operation, say
270 -- op :: forall ab. C a => forall c. Ix c => (b,c) -> a
271 -- Instantiate it at [ty1,ty2]
272 -- Return the "local method type":
273 -- forall c. Ix x => (ty2,c) -> ty1
274 instantiateMethod clas sel_id inst_tys
275 = ASSERT( ok_first_pred ) local_meth_ty
277 (sel_tyvars,sel_rho) = tcSplitForAllTys (idType sel_id)
278 rho_ty = ASSERT( length sel_tyvars == length inst_tys )
279 substTyWith sel_tyvars inst_tys sel_rho
281 (first_pred, local_meth_ty) = tcSplitPredFunTy_maybe rho_ty
282 `orElse` pprPanic "tcInstanceMethod" (ppr sel_id)
284 ok_first_pred = case getClassPredTys_maybe first_pred of
285 Just (clas1, _tys) -> clas == clas1
287 -- The first predicate should be of form (C a b)
288 -- where C is the class in question
291 ---------------------------
292 findMethodBind :: Name -- Selector name
293 -> LHsBinds Name -- A group of bindings
294 -> Maybe (LHsBind Name) -- The binding
295 findMethodBind sel_name binds
296 = foldlBag mplus Nothing (mapBag f binds)
298 f bind@(L _ (FunBind { fun_id = L _ op_name }))
299 | op_name == sel_name
304 Note [Polymorphic methods]
305 ~~~~~~~~~~~~~~~~~~~~~~~~~~
308 op :: forall b. Ord b => a -> b -> b -> b
309 instance Foo c => Foo [c] where
312 When typechecking the binding 'op = e', we'll have a meth_id for op
314 op :: forall c. Foo c => forall b. Ord b => [c] -> b -> b -> b
316 So tcPolyBinds must be capable of dealing with nested polytypes;
317 and so it is. See TcBinds.tcMonoBinds (with type-sig case).
319 Note [Silly default-method bind]
320 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
321 When we pass the default method binding to the type checker, it must
324 otherwise the "$dm" stuff comes out error messages. But we want the
325 "$dm" to come out in the interface file. So we typecheck the former,
326 and wrap it in a let, thus
327 $dmop2 = let op2 = e in op2
328 This makes the error messages right.
331 %************************************************************************
333 Extracting generic instance declaration from class declarations
335 %************************************************************************
337 @getGenericInstances@ extracts the generic instance declarations from a class
338 declaration. For exmaple
343 op{ x+y } (Inl v) = ...
344 op{ x+y } (Inr v) = ...
345 op{ x*y } (v :*: w) = ...
348 gives rise to the instance declarations
350 instance C (x+y) where
354 instance C (x*y) where
361 mkGenericDefMethBind :: Class -> [Type] -> Id -> Name -> TcM (LHsBind Name)
362 mkGenericDefMethBind clas inst_tys sel_id dm_name
363 = -- A generic default method
364 -- If the method is defined generically, we only have to call the
366 do { dflags <- getDOpts
367 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Filling in method body"
368 (vcat [ppr clas <+> ppr inst_tys,
369 nest 2 (ppr sel_id <+> equals <+> ppr rhs)]))
371 ; return (noLoc $ mkFunBind (noLoc (idName sel_id))
372 [mkSimpleMatch [] rhs]) }
374 rhs = nlHsVar dm_name
376 ---------------------------
377 getGenericInstances :: [LTyClDecl Name] -> TcM [InstInfo Name]
378 getGenericInstances class_decls
379 = do { gen_inst_infos <- mapM (addLocM get_generics) class_decls
380 ; let { gen_inst_info = concat gen_inst_infos }
382 -- Return right away if there is no generic stuff
383 ; if null gen_inst_info then return []
386 -- Otherwise print it out
387 { dumpDerivingInfo $ hang (ptext (sLit "Generic instances"))
388 2 (vcat (map pprInstInfoDetails gen_inst_info))
389 ; return gen_inst_info }}
391 get_generics :: TyClDecl Name -> TcM [InstInfo Name]
392 get_generics decl@(ClassDecl {tcdLName = class_name, tcdMeths = def_methods})
394 = return [] -- The comon case: no generic default methods
396 | otherwise -- A source class decl with generic default methods
397 = recoverM (return []) $
398 tcAddDeclCtxt decl $ do
399 clas <- tcLookupLocatedClass class_name
401 -- Group by type, and
402 -- make an InstInfo out of each group
404 groups = groupWith listToBag generic_binds
406 inst_infos <- mapM (mkGenericInstance clas) groups
408 -- Check that there is only one InstInfo for each type constructor
409 -- The main way this can fail is if you write
410 -- f {| a+b |} ... = ...
411 -- f {| x+y |} ... = ...
412 -- Then at this point we'll have an InstInfo for each
414 -- The class should be unary, which is why simpleInstInfoTyCon should be ok
416 tc_inst_infos :: [(TyCon, InstInfo Name)]
417 tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
419 bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
420 group `lengthExceeds` 1]
421 get_uniq (tc,_) = getUnique tc
423 mapM_ (addErrTc . dupGenericInsts) bad_groups
425 -- Check that there is an InstInfo for each generic type constructor
427 missing = genericTyConNames `minusList` [tyConName tc | (tc,_) <- tc_inst_infos]
429 checkTc (null missing) (missingGenericInstances missing)
433 generic_binds :: [(HsType Name, LHsBind Name)]
434 generic_binds = getGenericBinds def_methods
435 get_generics decl = pprPanic "get_generics" (ppr decl)
438 ---------------------------------
439 getGenericBinds :: LHsBinds Name -> [(HsType Name, LHsBind Name)]
440 -- Takes a group of method bindings, finds the generic ones, and returns
441 -- them in finite map indexed by the type parameter in the definition.
442 getGenericBinds binds = concat (map getGenericBind (bagToList binds))
444 getGenericBind :: LHsBindLR Name Name -> [(HsType Name, LHsBindLR Name Name)]
445 getGenericBind (L loc bind@(FunBind { fun_matches = MatchGroup matches ty }))
446 = groupWith wrap (mapCatMaybes maybeGenericMatch matches)
448 wrap ms = L loc (bind { fun_matches = MatchGroup ms ty })
452 groupWith :: ([a] -> b) -> [(HsType Name, a)] -> [(HsType Name, b)]
454 groupWith op ((t,v):prs) = (t, op (v:vs)) : groupWith op rest
457 (this,rest) = partition same_t prs
458 same_t (t', _v) = t `eqPatType` t'
460 eqPatLType :: LHsType Name -> LHsType Name -> Bool
461 eqPatLType t1 t2 = unLoc t1 `eqPatType` unLoc t2
463 eqPatType :: HsType Name -> HsType Name -> Bool
464 -- A very simple equality function, only for
465 -- type patterns in generic function definitions.
466 eqPatType (HsTyVar v1) (HsTyVar v2) = v1==v2
467 eqPatType (HsAppTy s1 t1) (HsAppTy s2 t2) = s1 `eqPatLType` s2 && t1 `eqPatLType` t2
468 eqPatType (HsOpTy s1 op1 t1) (HsOpTy s2 op2 t2) = s1 `eqPatLType` s2 && t1 `eqPatLType` t2 && unLoc op1 == unLoc op2
469 eqPatType (HsNumTy n1) (HsNumTy n2) = n1 == n2
470 eqPatType (HsParTy t1) t2 = unLoc t1 `eqPatType` t2
471 eqPatType t1 (HsParTy t2) = t1 `eqPatType` unLoc t2
472 eqPatType _ _ = False
474 ---------------------------------
475 mkGenericInstance :: Class
476 -> (HsType Name, LHsBinds Name)
477 -> TcM (InstInfo Name)
479 mkGenericInstance clas (hs_ty, binds) = do
480 -- Make a generic instance declaration
481 -- For example: instance (C a, C b) => C (a+b) where { binds }
483 -- Extract the universally quantified type variables
484 -- and wrap them as forall'd tyvars, so that kind inference
485 -- works in the standard way
487 sig_tvs = userHsTyVarBndrs $ map noLoc $ nameSetToList $
488 extractHsTyVars (noLoc hs_ty)
489 hs_forall_ty = noLoc $ mkExplicitHsForAllTy sig_tvs (noLoc []) (noLoc hs_ty)
491 -- Type-check the instance type, and check its form
492 forall_inst_ty <- tcHsSigType GenPatCtxt hs_forall_ty
494 (tyvars, inst_ty) = tcSplitForAllTys forall_inst_ty
496 checkTc (validGenericInstanceType inst_ty)
497 (badGenericInstanceType binds)
499 -- Make the dictionary function.
501 overlap_flag <- getOverlapFlag
502 dfun_name <- newDFunName clas [inst_ty] span
504 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
505 dfun_id = mkDictFunId dfun_name tyvars inst_theta clas [inst_ty]
506 ispec = mkLocalInstance dfun_id overlap_flag
508 return (InstInfo { iSpec = ispec, iBinds = VanillaInst binds [] False })
512 %************************************************************************
516 %************************************************************************
519 tcAddDeclCtxt :: TyClDecl Name -> TcM a -> TcM a
520 tcAddDeclCtxt decl thing_inside
521 = addErrCtxt ctxt thing_inside
523 thing | isClassDecl decl = "class"
524 | isTypeDecl decl = "type synonym" ++ maybeInst
525 | isDataDecl decl = if tcdND decl == NewType
526 then "newtype" ++ maybeInst
527 else "data type" ++ maybeInst
528 | isFamilyDecl decl = "family"
529 | otherwise = panic "tcAddDeclCtxt/thing"
531 maybeInst | isFamInstDecl decl = " instance"
534 ctxt = hsep [ptext (sLit "In the"), text thing,
535 ptext (sLit "declaration for"), quotes (ppr (tcdName decl))]
537 badMethodErr :: Outputable a => a -> Name -> SDoc
539 = hsep [ptext (sLit "Class"), quotes (ppr clas),
540 ptext (sLit "does not have a method"), quotes (ppr op)]
542 badGenericMethod :: Outputable a => a -> Name -> SDoc
543 badGenericMethod clas op
544 = hsep [ptext (sLit "Class"), quotes (ppr clas),
545 ptext (sLit "has a generic-default signature without a binding"), quotes (ppr op)]
547 badATErr :: Class -> Name -> SDoc
549 = hsep [ptext (sLit "Class"), quotes (ppr clas),
550 ptext (sLit "does not have an associated type"), quotes (ppr at)]
552 omittedATWarn :: Name -> SDoc
554 = ptext (sLit "No explicit AT declaration for") <+> quotes (ppr at)
556 badGenericInstanceType :: LHsBinds Name -> SDoc
557 badGenericInstanceType binds
558 = vcat [ptext (sLit "Illegal type pattern in the generic bindings"),
561 missingGenericInstances :: [Name] -> SDoc
562 missingGenericInstances missing
563 = ptext (sLit "Missing type patterns for") <+> pprQuotedList missing
565 dupGenericInsts :: [(TyCon, InstInfo a)] -> SDoc
566 dupGenericInsts tc_inst_infos
567 = vcat [ptext (sLit "More than one type pattern for a single generic type constructor:"),
568 nest 2 (vcat (map ppr_inst_ty tc_inst_infos)),
569 ptext (sLit "All the type patterns for a generic type constructor must be identical")
572 ppr_inst_ty (_,inst) = ppr (simpleInstInfoTy inst)