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, mkDefMethRdrName,
12 tcAddDeclCtxt, badMethodErr, badATErr, omittedATWarn
15 #include "HsVersions.h"
59 Every class implicitly declares a new data type, corresponding to dictionaries
60 of that class. So, for example:
62 class (D a) => C a where
64 op2 :: forall b. Ord b => a -> b -> b
66 would implicitly declare
68 data CDict a = CDict (D a)
70 (forall b. Ord b => a -> b -> b)
72 (We could use a record decl, but that means changing more of the existing apparatus.
75 For classes with just one superclass+method, we use a newtype decl instead:
78 op :: forallb. a -> b -> b
82 newtype CDict a = CDict (forall b. a -> b -> b)
84 Now DictTy in Type is just a form of type synomym:
85 DictTy c t = TyConTy CDict `AppTy` t
87 Death to "ExpandingDicts".
90 %************************************************************************
92 Type-checking the class op signatures
94 %************************************************************************
97 tcClassSigs :: Name -- Name of the class
102 type TcMethInfo = (Name, DefMeth, Type) -- A temporary intermediate, to communicate
103 -- between tcClassSigs and buildClass
104 tcClassSigs clas sigs def_methods
105 = do { dm_env <- checkDefaultBinds clas op_names def_methods
106 ; mapM (tcClassSig dm_env) op_sigs }
108 op_sigs = [sig | sig@(L _ (TypeSig _ _)) <- sigs]
109 op_names = [n | (L _ (TypeSig (L _ n) _)) <- op_sigs]
112 checkDefaultBinds :: Name -> [Name] -> LHsBinds Name -> TcM (NameEnv Bool)
113 -- Check default bindings
114 -- a) must be for a class op for this class
115 -- b) must be all generic or all non-generic
116 -- and return a mapping from class-op to Bool
117 -- where True <=> it's a generic default method
118 checkDefaultBinds clas ops binds
119 = do dm_infos <- mapM (addLocM (checkDefaultBind clas ops)) (bagToList binds)
120 return (mkNameEnv dm_infos)
122 checkDefaultBind :: Name -> [Name] -> HsBindLR Name Name -> TcM (Name, Bool)
123 checkDefaultBind clas ops (FunBind {fun_id = L _ op, fun_matches = MatchGroup matches _ })
124 = do { -- Check that the op is from this class
125 checkTc (op `elem` ops) (badMethodErr clas op)
127 -- Check that all the defns ar generic, or none are
128 ; checkTc (all_generic || none_generic) (mixedGenericErr op)
130 ; return (op, all_generic)
133 n_generic = count (isJust . maybeGenericMatch) matches
134 none_generic = n_generic == 0
135 all_generic = matches `lengthIs` n_generic
136 checkDefaultBind _ _ b = pprPanic "checkDefaultBind" (ppr b)
139 tcClassSig :: NameEnv Bool -- Info about default methods;
143 tcClassSig dm_env (L loc (TypeSig (L _ op_name) op_hs_ty))
144 = setSrcSpan loc $ do
145 { op_ty <- tcHsKindedType op_hs_ty -- Class tyvars already in scope
146 ; let dm = case lookupNameEnv dm_env op_name of
148 Just False -> DefMeth
149 Just True -> GenDefMeth
150 ; return (op_name, dm, op_ty) }
151 tcClassSig _ s = pprPanic "tcClassSig" (ppr s)
155 %************************************************************************
159 %************************************************************************
162 tcClassDecl2 :: LTyClDecl Name -- The class declaration
163 -> TcM ([Id], LHsBinds Id)
165 tcClassDecl2 (L loc (ClassDecl {tcdLName = class_name, tcdSigs = sigs,
166 tcdMeths = default_binds}))
167 = recoverM (return ([], emptyLHsBinds)) $
169 do { clas <- tcLookupLocatedClass class_name
171 -- We make a separate binding for each default method.
172 -- At one time I used a single AbsBinds for all of them, thus
173 -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
174 -- But that desugars into
175 -- ds = \d -> (..., ..., ...)
176 -- dm1 = \d -> case ds d of (a,b,c) -> a
177 -- And since ds is big, it doesn't get inlined, so we don't get good
178 -- default methods. Better to make separate AbsBinds for each
180 (tyvars, _, _, op_items) = classBigSig clas
181 rigid_info = ClsSkol clas
182 prag_fn = mkPragFun sigs default_binds
183 sig_fn = mkTcSigFun sigs
184 clas_tyvars = tcSkolSigTyVars rigid_info tyvars
185 pred = mkClassPred clas (mkTyVarTys clas_tyvars)
186 ; inst_loc <- getInstLoc (SigOrigin rigid_info)
187 ; this_dict <- newDictBndr inst_loc pred
189 ; let tc_dm = tcDefMeth clas clas_tyvars
190 this_dict default_binds
192 -- tc_dm is called only for a sel_id
193 -- that has a binding in default_binds
195 dm_sel_ids = [sel_id | (sel_id, DefMeth) <- op_items]
196 -- Generate code for polymorphic default methods only (hence DefMeth)
197 -- (Generic default methods have turned into instance decls by now.)
198 -- This is incompatible with Hugs, which expects a polymorphic
199 -- default method for every class op, regardless of whether or not
200 -- the programmer supplied an explicit default decl for the class.
201 -- (If necessary we can fix that, but we don't have a convenient Id to hand.)
203 ; (dm_ids, defm_binds) <- tcExtendTyVarEnv clas_tyvars $
204 mapAndUnzipM tc_dm dm_sel_ids
206 ; return (dm_ids, listToBag defm_binds) }
208 tcClassDecl2 d = pprPanic "tcClassDecl2" (ppr d)
210 tcDefMeth :: Class -> [TyVar] -> Inst -> LHsBinds Name
211 -> TcSigFun -> TcPragFun -> Id
212 -> TcM (Id, LHsBind Id)
213 tcDefMeth clas tyvars this_dict binds_in sig_fn prag_fn sel_id
214 = do { let sel_name = idName sel_id
215 ; dm_name <- lookupTopBndrRn (mkDefMethRdrName sel_name)
216 ; local_dm_name <- newLocalName sel_name
217 -- Base the local_dm_name on the selector name, becuase
218 -- type errors from tcInstanceMethodBody come from here
220 -- See Note [Silly default-method bind]
221 -- (possibly out of date)
223 ; let meth_bind = findMethodBind sel_name local_dm_name binds_in
224 `orElse` pprPanic "tcDefMeth" (ppr sel_id)
225 -- We only call tcDefMeth on selectors for which
226 -- there is a binding in binds_in
228 dm_sig_fn _ = sig_fn sel_name
229 dm_ty = idType sel_id
230 dm_id = mkDefaultMethodId dm_name dm_ty
231 local_dm_type = instantiateMethod clas sel_id (mkTyVarTys tyvars)
232 local_dm_id = mkLocalId local_dm_name local_dm_type
234 ; (dm_id_w_inline, spec_prags)
235 <- tcPrags NonRecursive False True dm_id (prag_fn sel_name)
237 ; warnTc (not (null spec_prags))
238 (ptext (sLit "Ignoring SPECIALISE pragmas on default method")
239 <+> quotes (ppr sel_name))
241 ; tcInstanceMethodBody (instLoc this_dict)
244 dm_id_w_inline local_dm_id
245 dm_sig_fn IsDefaultMethod meth_bind }
248 tcInstanceMethodBody :: InstLoc -> [TcTyVar] -> [Inst]
249 -> ([Inst], LHsBinds Id) -> Id -> Id
250 -> TcSigFun -> TcSpecPrags -> LHsBind Name
251 -> TcM (Id, LHsBind Id)
252 tcInstanceMethodBody inst_loc tyvars dfun_dicts
253 (this_dict, this_bind) meth_id local_meth_id
254 meth_sig_fn spec_prags bind@(L loc _)
255 = do { -- Typecheck the binding, first extending the envt
256 -- so that when tcInstSig looks up the local_meth_id to find
257 -- its signature, we'll find it in the environment
258 ; ((tc_bind, _), lie) <- getLIE $
259 tcExtendIdEnv [local_meth_id] $
260 tcPolyBinds TopLevel meth_sig_fn no_prag_fn
261 NonRecursive NonRecursive
264 ; let avails = this_dict ++ dfun_dicts
265 -- Only need the this_dict stuff if there are type
266 -- variables involved; otherwise overlap is not possible
267 -- See Note [Subtle interaction of recursion and overlap]
269 ; lie_binds <- tcSimplifyCheck inst_loc tyvars avails lie
271 ; let full_bind = AbsBinds tyvars dfun_lam_vars
272 [(tyvars, meth_id, local_meth_id, spec_prags)]
273 (this_bind `unionBags` lie_binds
276 dfun_lam_vars = map instToVar dfun_dicts -- Includes equalities
278 ; return (meth_id, L loc full_bind) }
280 no_prag_fn _ = [] -- No pragmas for local_meth_id;
281 -- they are all for meth_id
285 mkDefMethRdrName :: Name -> RdrName
286 mkDefMethRdrName sel_name = mkDerivedRdrName sel_name mkDefaultMethodOcc
288 instantiateMethod :: Class -> Id -> [TcType] -> TcType
289 -- Take a class operation, say
290 -- op :: forall ab. C a => forall c. Ix c => (b,c) -> a
291 -- Instantiate it at [ty1,ty2]
292 -- Return the "local method type":
293 -- forall c. Ix x => (ty2,c) -> ty1
294 instantiateMethod clas sel_id inst_tys
295 = ASSERT( ok_first_pred ) local_meth_ty
297 (sel_tyvars,sel_rho) = tcSplitForAllTys (idType sel_id)
298 rho_ty = ASSERT( length sel_tyvars == length inst_tys )
299 substTyWith sel_tyvars inst_tys sel_rho
301 (first_pred, local_meth_ty) = tcSplitPredFunTy_maybe rho_ty
302 `orElse` pprPanic "tcInstanceMethod" (ppr sel_id)
304 ok_first_pred = case getClassPredTys_maybe first_pred of
305 Just (clas1, _tys) -> clas == clas1
307 -- The first predicate should be of form (C a b)
308 -- where C is the class in question
311 ---------------------------
312 -- The renamer just puts the selector ID as the binder in the method binding
313 -- but we must use the method name; so we substitute it here. Crude but simple.
314 findMethodBind :: Name -> Name -- Selector and method name
315 -> LHsBinds Name -- A group of bindings
316 -> Maybe (LHsBind Name) -- The binding, with meth_name replacing sel_name
317 findMethodBind sel_name meth_name binds
318 = foldlBag mplus Nothing (mapBag f binds)
320 f (L loc1 bind@(FunBind { fun_id = L loc2 op_name }))
321 | op_name == sel_name
322 = Just (L loc1 (bind { fun_id = L loc2 meth_name }))
326 Note [Polymorphic methods]
327 ~~~~~~~~~~~~~~~~~~~~~~~~~~
330 op :: forall b. Ord b => a -> b -> b -> b
331 instance Foo c => Foo [c] where
334 When typechecking the binding 'op = e', we'll have a meth_id for op
336 op :: forall c. Foo c => forall b. Ord b => [c] -> b -> b -> b
338 So tcPolyBinds must be capable of dealing with nested polytypes;
339 and so it is. See TcBinds.tcMonoBinds (with type-sig case).
341 Note [Silly default-method bind]
342 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
343 When we pass the default method binding to the type checker, it must
346 otherwise the "$dm" stuff comes out error messages. But we want the
347 "$dm" to come out in the interface file. So we typecheck the former,
348 and wrap it in a let, thus
349 $dmop2 = let op2 = e in op2
350 This makes the error messages right.
353 %************************************************************************
355 Extracting generic instance declaration from class declarations
357 %************************************************************************
359 @getGenericInstances@ extracts the generic instance declarations from a class
360 declaration. For exmaple
365 op{ x+y } (Inl v) = ...
366 op{ x+y } (Inr v) = ...
367 op{ x*y } (v :*: w) = ...
370 gives rise to the instance declarations
372 instance C (x+y) where
376 instance C (x*y) where
383 mkGenericDefMethBind :: Class -> [Type] -> Id -> Name -> TcM (LHsBind Name)
384 mkGenericDefMethBind clas inst_tys sel_id meth_name
385 = -- A generic default method
386 -- If the method is defined generically, we can only do the job if the
387 -- instance declaration is for a single-parameter type class with
388 -- a type constructor applied to type arguments in the instance decl
389 -- (checkTc, so False provokes the error)
390 do { checkTc (isJust maybe_tycon)
391 (badGenericInstance sel_id (notSimple inst_tys))
392 ; checkTc (tyConHasGenerics tycon)
393 (badGenericInstance sel_id (notGeneric tycon))
396 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Filling in method body"
397 (vcat [ppr clas <+> ppr inst_tys,
398 nest 2 (ppr sel_id <+> equals <+> ppr rhs)]))
400 -- Rename it before returning it
401 ; (rn_rhs, _) <- rnLExpr rhs
402 ; return (noLoc $ mkFunBind (noLoc meth_name) [mkSimpleMatch [] rn_rhs]) }
404 rhs = mkGenericRhs sel_id clas_tyvar tycon
406 -- The tycon is only used in the generic case, and in that
407 -- case we require that the instance decl is for a single-parameter
408 -- type class with type variable arguments:
409 -- instance (...) => C (T a b)
410 clas_tyvar = ASSERT (not (null (classTyVars clas))) head (classTyVars clas)
411 Just tycon = maybe_tycon
412 maybe_tycon = case inst_tys of
413 [ty] -> case tcSplitTyConApp_maybe ty of
414 Just (tycon, arg_tys) | all tcIsTyVarTy arg_tys -> Just tycon
419 ---------------------------
420 getGenericInstances :: [LTyClDecl Name] -> TcM [InstInfo Name]
421 getGenericInstances class_decls
422 = do { gen_inst_infos <- mapM (addLocM get_generics) class_decls
423 ; let { gen_inst_info = concat gen_inst_infos }
425 -- Return right away if there is no generic stuff
426 ; if null gen_inst_info then return []
429 -- Otherwise print it out
431 ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances"
432 (vcat (map pprInstInfoDetails gen_inst_info)))
433 ; return gen_inst_info }}
435 get_generics :: TyClDecl Name -> TcM [InstInfo Name]
436 get_generics decl@(ClassDecl {tcdLName = class_name, tcdMeths = def_methods})
438 = return [] -- The comon case: no generic default methods
440 | otherwise -- A source class decl with generic default methods
441 = recoverM (return []) $
442 tcAddDeclCtxt decl $ do
443 clas <- tcLookupLocatedClass class_name
445 -- Group by type, and
446 -- make an InstInfo out of each group
448 groups = groupWith listToBag generic_binds
450 inst_infos <- mapM (mkGenericInstance clas) groups
452 -- Check that there is only one InstInfo for each type constructor
453 -- The main way this can fail is if you write
454 -- f {| a+b |} ... = ...
455 -- f {| x+y |} ... = ...
456 -- Then at this point we'll have an InstInfo for each
458 -- The class should be unary, which is why simpleInstInfoTyCon should be ok
460 tc_inst_infos :: [(TyCon, InstInfo Name)]
461 tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
463 bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
464 group `lengthExceeds` 1]
465 get_uniq (tc,_) = getUnique tc
467 mapM_ (addErrTc . dupGenericInsts) bad_groups
469 -- Check that there is an InstInfo for each generic type constructor
471 missing = genericTyConNames `minusList` [tyConName tc | (tc,_) <- tc_inst_infos]
473 checkTc (null missing) (missingGenericInstances missing)
477 generic_binds :: [(HsType Name, LHsBind Name)]
478 generic_binds = getGenericBinds def_methods
479 get_generics decl = pprPanic "get_generics" (ppr decl)
482 ---------------------------------
483 getGenericBinds :: LHsBinds Name -> [(HsType Name, LHsBind Name)]
484 -- Takes a group of method bindings, finds the generic ones, and returns
485 -- them in finite map indexed by the type parameter in the definition.
486 getGenericBinds binds = concat (map getGenericBind (bagToList binds))
488 getGenericBind :: LHsBindLR Name Name -> [(HsType Name, LHsBindLR Name Name)]
489 getGenericBind (L loc bind@(FunBind { fun_matches = MatchGroup matches ty }))
490 = groupWith wrap (mapCatMaybes maybeGenericMatch matches)
492 wrap ms = L loc (bind { fun_matches = MatchGroup ms ty })
496 groupWith :: ([a] -> b) -> [(HsType Name, a)] -> [(HsType Name, b)]
498 groupWith op ((t,v):prs) = (t, op (v:vs)) : groupWith op rest
501 (this,rest) = partition same_t prs
502 same_t (t', _v) = t `eqPatType` t'
504 eqPatLType :: LHsType Name -> LHsType Name -> Bool
505 eqPatLType t1 t2 = unLoc t1 `eqPatType` unLoc t2
507 eqPatType :: HsType Name -> HsType Name -> Bool
508 -- A very simple equality function, only for
509 -- type patterns in generic function definitions.
510 eqPatType (HsTyVar v1) (HsTyVar v2) = v1==v2
511 eqPatType (HsAppTy s1 t1) (HsAppTy s2 t2) = s1 `eqPatLType` s2 && t1 `eqPatLType` t2
512 eqPatType (HsOpTy s1 op1 t1) (HsOpTy s2 op2 t2) = s1 `eqPatLType` s2 && t1 `eqPatLType` t2 && unLoc op1 == unLoc op2
513 eqPatType (HsNumTy n1) (HsNumTy n2) = n1 == n2
514 eqPatType (HsParTy t1) t2 = unLoc t1 `eqPatType` t2
515 eqPatType t1 (HsParTy t2) = t1 `eqPatType` unLoc t2
516 eqPatType _ _ = False
518 ---------------------------------
519 mkGenericInstance :: Class
520 -> (HsType Name, LHsBinds Name)
521 -> TcM (InstInfo Name)
523 mkGenericInstance clas (hs_ty, binds) = do
524 -- Make a generic instance declaration
525 -- For example: instance (C a, C b) => C (a+b) where { binds }
527 -- Extract the universally quantified type variables
528 -- and wrap them as forall'd tyvars, so that kind inference
529 -- works in the standard way
531 sig_tvs = map (noLoc.UserTyVar) (nameSetToList (extractHsTyVars (noLoc hs_ty)))
532 hs_forall_ty = noLoc $ mkExplicitHsForAllTy sig_tvs (noLoc []) (noLoc hs_ty)
534 -- Type-check the instance type, and check its form
535 forall_inst_ty <- tcHsSigType GenPatCtxt hs_forall_ty
537 (tyvars, inst_ty) = tcSplitForAllTys forall_inst_ty
539 checkTc (validGenericInstanceType inst_ty)
540 (badGenericInstanceType binds)
542 -- Make the dictionary function.
544 overlap_flag <- getOverlapFlag
545 dfun_name <- newDFunName clas [inst_ty] span
547 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
548 dfun_id = mkDictFunId dfun_name tyvars inst_theta clas [inst_ty]
549 ispec = mkLocalInstance dfun_id overlap_flag
551 return (InstInfo { iSpec = ispec, iBinds = VanillaInst binds [] False })
555 %************************************************************************
559 %************************************************************************
562 tcAddDeclCtxt :: TyClDecl Name -> TcM a -> TcM a
563 tcAddDeclCtxt decl thing_inside
564 = addErrCtxt ctxt thing_inside
566 thing | isClassDecl decl = "class"
567 | isTypeDecl decl = "type synonym" ++ maybeInst
568 | isDataDecl decl = if tcdND decl == NewType
569 then "newtype" ++ maybeInst
570 else "data type" ++ maybeInst
571 | isFamilyDecl decl = "family"
572 | otherwise = panic "tcAddDeclCtxt/thing"
574 maybeInst | isFamInstDecl decl = " instance"
577 ctxt = hsep [ptext (sLit "In the"), text thing,
578 ptext (sLit "declaration for"), quotes (ppr (tcdName decl))]
580 badMethodErr :: Outputable a => a -> Name -> SDoc
582 = hsep [ptext (sLit "Class"), quotes (ppr clas),
583 ptext (sLit "does not have a method"), quotes (ppr op)]
585 badATErr :: Class -> Name -> SDoc
587 = hsep [ptext (sLit "Class"), quotes (ppr clas),
588 ptext (sLit "does not have an associated type"), quotes (ppr at)]
590 omittedATWarn :: Name -> SDoc
592 = ptext (sLit "No explicit AT declaration for") <+> quotes (ppr at)
594 badGenericInstance :: Var -> SDoc -> SDoc
595 badGenericInstance sel_id because
596 = sep [ptext (sLit "Can't derive generic code for") <+> quotes (ppr sel_id),
599 notSimple :: [Type] -> SDoc
601 = vcat [ptext (sLit "because the instance type(s)"),
602 nest 2 (ppr inst_tys),
603 ptext (sLit "is not a simple type of form (T a1 ... an)")]
605 notGeneric :: TyCon -> SDoc
607 = vcat [ptext (sLit "because the instance type constructor") <+> quotes (ppr tycon) <+>
608 ptext (sLit "was not compiled with -XGenerics")]
610 badGenericInstanceType :: LHsBinds Name -> SDoc
611 badGenericInstanceType binds
612 = vcat [ptext (sLit "Illegal type pattern in the generic bindings"),
615 missingGenericInstances :: [Name] -> SDoc
616 missingGenericInstances missing
617 = ptext (sLit "Missing type patterns for") <+> pprQuotedList missing
619 dupGenericInsts :: [(TyCon, InstInfo a)] -> SDoc
620 dupGenericInsts tc_inst_infos
621 = vcat [ptext (sLit "More than one type pattern for a single generic type constructor:"),
622 nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
623 ptext (sLit "All the type patterns for a generic type constructor must be identical")
626 ppr_inst_ty (_,inst) = ppr (simpleInstInfoTy inst)
628 mixedGenericErr :: Name -> SDoc
630 = ptext (sLit "Can't mix generic and non-generic equations for class method") <+> quotes (ppr op)