2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcClassDcl]{Typechecking class declarations}
7 module TcClassDcl ( tcClassDecl1, tcClassDecls2,
8 tcMethodBind, mkMethodBind, badMethodErr
11 #include "HsVersions.h"
13 import HsSyn ( TyClDecl(..), Sig(..), MonoBinds(..),
14 HsExpr(..), HsLit(..),
15 mkSimpleMatch, andMonoBinds, andMonoBindList,
16 isClassOpSig, isPragSig,
17 getClassDeclSysNames, placeHolderType
19 import BasicTypes ( RecFlag(..), StrictnessMark(..) )
20 import RnHsSyn ( RenamedTyClDecl,
21 RenamedClassOpSig, RenamedMonoBinds,
24 import TcHsSyn ( TcMonoBinds )
26 import Inst ( Inst, InstOrigin(..), LIE, emptyLIE, plusLIE, plusLIEs,
27 instToId, newDicts, newMethod )
28 import TcEnv ( TyThingDetails(..),
29 tcLookupClass, tcExtendTyVarEnv2,
32 import TcBinds ( tcMonoBinds )
33 import TcMonoType ( TcSigInfo(..), tcHsType, tcHsTheta, mkTcSig )
34 import TcSimplify ( tcSimplifyCheck )
35 import TcUnify ( checkSigTyVars, sigCtxt )
36 import TcMType ( tcInstTyVars, checkValidTheta, checkValidType, SourceTyCtxt(..), UserTypeCtxt(..) )
37 import TcType ( Type, TyVarDetails(..), TcType, TcThetaType, TcTyVar,
38 mkTyVarTys, mkPredTys, mkClassPred,
39 tcIsTyVarTy, tcSplitTyConApp_maybe, tcSplitSigmaTy
42 import Generics ( mkGenericRhs )
43 import PrelInfo ( nO_METHOD_BINDING_ERROR_ID )
44 import Class ( classTyVars, classBigSig, classTyCon, className,
45 Class, ClassOpItem, DefMeth (..) )
46 import MkId ( mkDictSelId, mkDataConId, mkDataConWrapId, mkDefaultMethodId )
47 import DataCon ( mkDataCon )
48 import Id ( Id, idType, idName, setIdLocalExported )
49 import Module ( Module )
50 import Name ( Name, NamedThing(..) )
51 import NameEnv ( NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, plusNameEnv )
52 import NameSet ( emptyNameSet )
56 import ErrUtils ( dumpIfSet )
57 import Util ( count, isSingleton, lengthIs, equalLength )
58 import Maybes ( seqMaybe, maybeToBool )
65 Every class implicitly declares a new data type, corresponding to dictionaries
66 of that class. So, for example:
68 class (D a) => C a where
70 op2 :: forall b. Ord b => a -> b -> b
72 would implicitly declare
74 data CDict a = CDict (D a)
76 (forall b. Ord b => a -> b -> b)
78 (We could use a record decl, but that means changing more of the existing apparatus.
81 For classes with just one superclass+method, we use a newtype decl instead:
84 op :: forallb. a -> b -> b
88 newtype CDict a = CDict (forall b. a -> b -> b)
90 Now DictTy in Type is just a form of type synomym:
91 DictTy c t = TyConTy CDict `AppTy` t
93 Death to "ExpandingDicts".
96 %************************************************************************
98 \subsection{Type checking}
100 %************************************************************************
104 tcClassDecl1 :: RenamedTyClDecl -> TcM (Name, TyThingDetails)
105 tcClassDecl1 (ClassDecl {tcdCtxt = context, tcdName = class_name,
106 tcdTyVars = tyvar_names, tcdFDs = fundeps,
107 tcdSigs = class_sigs, tcdMeths = def_methods,
108 tcdSysNames = sys_names, tcdLoc = src_loc})
109 = -- LOOK THINGS UP IN THE ENVIRONMENT
110 tcLookupClass class_name `thenTc` \ clas ->
112 tyvars = classTyVars clas
113 op_sigs = filter isClassOpSig class_sigs
114 op_names = [n | ClassOpSig n _ _ _ <- op_sigs]
115 (_, datacon_name, datacon_wkr_name, sc_sel_names) = getClassDeclSysNames sys_names
117 tcExtendTyVarEnv tyvars $
119 checkDefaultBinds clas op_names def_methods `thenTc` \ mb_dm_env ->
122 -- The renamer has already checked that the context mentions
123 -- only the type variable of the class decl.
124 -- Context is already kind-checked
125 ASSERT( equalLength context sc_sel_names )
126 tcHsTheta context `thenTc` \ sc_theta ->
128 -- CHECK THE CLASS SIGNATURES,
129 mapTc (tcClassSig clas tyvars mb_dm_env) op_sigs `thenTc` \ sig_stuff ->
131 -- MAKE THE CLASS DETAILS
133 (op_tys, op_items) = unzip sig_stuff
134 sc_tys = mkPredTys sc_theta
135 dict_component_tys = sc_tys ++ op_tys
136 sc_sel_ids = [mkDictSelId sc_name clas | sc_name <- sc_sel_names]
138 dict_con = mkDataCon datacon_name
139 [NotMarkedStrict | _ <- dict_component_tys]
140 [{- No labelled fields -}]
143 [{-No existential tyvars-}] [{-Or context-}]
146 dict_con_id dict_wrap_id
148 dict_con_id = mkDataConId datacon_wkr_name dict_con
149 dict_wrap_id = mkDataConWrapId dict_con
151 returnTc (class_name, ClassDetails sc_theta sc_sel_ids op_items dict_con)
155 checkDefaultBinds :: Class -> [Name] -> Maybe RenamedMonoBinds
156 -> TcM (Maybe (NameEnv Bool))
157 -- The returned environment says
158 -- x not in env => no default method
159 -- x -> True => generic default method
160 -- x -> False => polymorphic default method
162 -- Check default bindings
163 -- a) must be for a class op for this class
164 -- b) must be all generic or all non-generic
165 -- and return a mapping from class-op to DefMeth info
167 -- But do all this only for source binds
169 checkDefaultBinds clas ops Nothing
172 checkDefaultBinds clas ops (Just mbs)
173 = go mbs `thenTc` \ dm_env ->
174 returnTc (Just dm_env)
176 go EmptyMonoBinds = returnTc emptyNameEnv
178 go (AndMonoBinds b1 b2)
179 = go b1 `thenTc` \ dm_info1 ->
180 go b2 `thenTc` \ dm_info2 ->
181 returnTc (dm_info1 `plusNameEnv` dm_info2)
183 go (FunMonoBind op _ matches loc)
186 -- Check that the op is from this class
187 checkTc (op `elem` ops) (badMethodErr clas op) `thenTc_`
189 -- Check that all the defns ar generic, or none are
190 checkTc (all_generic || none_generic) (mixedGenericErr op) `thenTc_`
192 returnTc (unitNameEnv op all_generic)
194 n_generic = count (maybeToBool . maybeGenericMatch) matches
195 none_generic = n_generic == 0
196 all_generic = matches `lengthIs` n_generic
201 tcClassSig :: Class -- ...ditto...
202 -> [TyVar] -- The class type variable, used for error check only
203 -> Maybe (NameEnv Bool) -- Info about default methods;
204 -- Nothing => imported class defn with no method binds
206 -> TcM (Type, -- Type of the method
207 ClassOpItem) -- Selector Id, default-method Id, True if explicit default binding
209 -- This warrants an explanation: we need to separate generic
210 -- default methods and default methods later on in the compiler
211 -- so we distinguish them in checkDefaultBinds, and pass this knowledge in the
212 -- Class.DefMeth data structure.
214 tcClassSig clas clas_tyvars maybe_dm_env
215 (ClassOpSig op_name sig_dm op_ty src_loc)
216 = tcAddSrcLoc src_loc $
218 -- Check the type signature. NB that the envt *already has*
219 -- bindings for the type variables; see comments in TcTyAndClassDcls.
220 tcHsType op_ty `thenTc` \ local_ty ->
223 theta = [mkClassPred clas (mkTyVarTys clas_tyvars)]
225 -- Build the selector id and default method id
226 sel_id = mkDictSelId op_name clas
227 DefMeth dm_name = sig_dm
229 dm_info = case maybe_dm_env of
231 Just dm_env -> mk_src_dm_info dm_env
233 mk_src_dm_info dm_env = case lookupNameEnv dm_env op_name of
235 Just True -> GenDefMeth
236 Just False -> DefMeth dm_name
238 returnTc (local_ty, (sel_id, dm_info))
242 %************************************************************************
244 \subsection[Default methods]{Default methods}
246 %************************************************************************
248 The default methods for a class are each passed a dictionary for the
249 class, so that they get access to the other methods at the same type.
250 So, given the class decl
254 op2 :: Ord b => a -> b -> b -> b
257 op2 x y z = if (op1 x) && (y < z) then y else z
259 we get the default methods:
261 defm.Foo.op1 :: forall a. Foo a => a -> Bool
262 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
264 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
265 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
266 if (op1 a dfoo x) && (< b dord y z) then y else z
269 When we come across an instance decl, we may need to use the default
272 instance Foo Int where {}
276 const.Foo.Int.op1 :: Int -> Bool
277 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
279 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
280 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
282 dfun.Foo.Int :: Foo Int
283 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
285 Notice that, as with method selectors above, we assume that dictionary
286 application is curried, so there's no need to mention the Ord dictionary
287 in const.Foo.Int.op2 (or the type variable).
290 instance Foo a => Foo [a] where {}
292 dfun.Foo.List :: forall a. Foo a -> Foo [a]
294 = /\ a -> \ dfoo_a ->
296 op1 = defm.Foo.op1 [a] dfoo_list
297 op2 = defm.Foo.op2 [a] dfoo_list
298 dfoo_list = (op1, op2)
303 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
304 each local class decl.
307 tcClassDecls2 :: Module -> [RenamedTyClDecl] -> NF_TcM (LIE, TcMonoBinds, [Id])
309 tcClassDecls2 this_mod decls
311 (returnNF_Tc (emptyLIE, EmptyMonoBinds, []))
312 [tcClassDecl2 cls_decl | cls_decl@(ClassDecl {tcdMeths = Just _}) <- decls]
313 -- The 'Just' picks out source ClassDecls
315 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1, ids1) ->
316 tc2 `thenNF_Tc` \ (lie2, binds2, ids2) ->
317 returnNF_Tc (lie1 `plusLIE` lie2,
318 binds1 `AndMonoBinds` binds2,
322 @tcClassDecl2@ generates bindings for polymorphic default methods
323 (generic default methods have by now turned into instance declarations)
326 tcClassDecl2 :: RenamedTyClDecl -- The class declaration
327 -> NF_TcM (LIE, TcMonoBinds, [Id])
329 tcClassDecl2 (ClassDecl {tcdName = class_name, tcdSigs = sigs,
330 tcdMeths = Just default_binds, tcdLoc = src_loc})
331 = -- The 'Just' picks out source ClassDecls
332 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds, [])) $
333 tcAddSrcLoc src_loc $
334 tcLookupClass class_name `thenNF_Tc` \ clas ->
336 -- We make a separate binding for each default method.
337 -- At one time I used a single AbsBinds for all of them, thus
338 -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
339 -- But that desugars into
340 -- ds = \d -> (..., ..., ...)
341 -- dm1 = \d -> case ds d of (a,b,c) -> a
342 -- And since ds is big, it doesn't get inlined, so we don't get good
343 -- default methods. Better to make separate AbsBinds for each
345 (tyvars, _, _, op_items) = classBigSig clas
346 prags = filter isPragSig sigs
347 tc_dm = tcDefMeth clas tyvars default_binds prags
349 mapAndUnzip3Tc tc_dm op_items `thenTc` \ (defm_binds, const_lies, dm_ids_s) ->
351 returnTc (plusLIEs const_lies, andMonoBindList defm_binds, concat dm_ids_s)
354 tcDefMeth clas tyvars binds_in prags (_, NoDefMeth) = returnTc (EmptyMonoBinds, emptyLIE, [])
355 tcDefMeth clas tyvars binds_in prags (_, GenDefMeth) = returnTc (EmptyMonoBinds, emptyLIE, [])
356 -- Generate code for polymorphic default methods only
357 -- (Generic default methods have turned into instance decls by now.)
358 -- This is incompatible with Hugs, which expects a polymorphic
359 -- default method for every class op, regardless of whether or not
360 -- the programmer supplied an explicit default decl for the class.
361 -- (If necessary we can fix that, but we don't have a convenient Id to hand.)
363 tcDefMeth clas tyvars binds_in prags op_item@(sel_id, DefMeth dm_name)
364 = tcInstTyVars ClsTv tyvars `thenNF_Tc` \ (clas_tyvars, inst_tys, _) ->
366 dm_ty = idType sel_id -- Same as dict selector!
367 -- The default method's type should really come from the
368 -- iface file, since it could be usage-generalised, but this
369 -- requires altering the mess of knots in TcModule and I'm
370 -- too scared to do that. Instead, I have disabled generalisation
371 -- of types of default methods (and dict funs) by annotating them
372 -- TyGenNever (in MkId). Ugh! KSW 1999-09.
374 theta = [mkClassPred clas inst_tys]
375 dm_id = mkDefaultMethodId dm_name dm_ty
376 local_dm_id = setIdLocalExported dm_id
377 -- Reason for setIdLocalExported: see notes with MkId.mkDictFunId
378 xtve = tyvars `zip` clas_tyvars
380 newDicts origin theta `thenNF_Tc` \ [this_dict] ->
382 mkMethodBind origin clas inst_tys binds_in op_item `thenTc` \ (dm_inst, meth_info) ->
383 tcMethodBind xtve clas_tyvars theta
384 [this_dict] meth_info `thenTc` \ (defm_bind, insts_needed) ->
386 tcAddErrCtxt (defltMethCtxt clas) $
390 (ptext SLIT("class") <+> ppr clas)
393 insts_needed `thenTc` \ (const_lie, dict_binds) ->
395 -- Simplification can do unification
396 checkSigTyVars clas_tyvars `thenTc` \ clas_tyvars' ->
402 [(clas_tyvars', local_dm_id, instToId dm_inst)]
403 emptyNameSet -- No inlines (yet)
404 (dict_binds `andMonoBinds` defm_bind)
406 returnTc (full_bind, const_lie, [dm_id])
408 origin = ClassDeclOrigin
413 %************************************************************************
415 \subsection{Typechecking a method}
417 %************************************************************************
419 @tcMethodBind@ is used to type-check both default-method and
420 instance-decl method declarations. We must type-check methods one at a
421 time, because their signatures may have different contexts and
426 :: [(TyVar,TcTyVar)] -- Bindings for type environment
427 -> [TcTyVar] -- Instantiated type variables for the
428 -- enclosing class/instance decl.
429 -- They'll be signature tyvars, and we
430 -- want to check that they don't get bound
431 -- Always equal the range of the type envt
432 -> TcThetaType -- Available theta; it's just used for the error message
433 -> [Inst] -- Available from context, used to simplify constraints
434 -- from the method body
435 -> (Id, TcSigInfo, RenamedMonoBinds) -- Details of this method
436 -> TcM (TcMonoBinds, LIE)
438 tcMethodBind xtve inst_tyvars inst_theta avail_insts
439 (sel_id, meth_sig, meth_bind)
441 -- Check the bindings; first adding inst_tyvars to the envt
442 -- so that we don't quantify over them in nested places
443 tcExtendTyVarEnv2 xtve (
444 tcAddErrCtxt (methodCtxt sel_id) $
445 tcMonoBinds meth_bind [meth_sig] NonRecursive
446 ) `thenTc` \ (meth_bind, meth_lie, _, _) ->
448 -- Now do context reduction. We simplify wrt both the local tyvars
449 -- and the ones of the class/instance decl, so that there is
452 -- op :: Eq a => a -> b -> a
454 -- We do this for each method independently to localise error messages
457 TySigInfo meth_id meth_tvs meth_theta _ local_meth_id _ _ = meth_sig
459 tcAddErrCtxtM (sigCtxt sel_id inst_tyvars inst_theta (idType meth_id)) $
460 newDicts SignatureOrigin meth_theta `thenNF_Tc` \ meth_dicts ->
462 all_tyvars = meth_tvs ++ inst_tyvars
463 all_insts = avail_insts ++ meth_dicts
466 (ptext SLIT("class or instance method") <+> quotes (ppr sel_id))
467 all_tyvars all_insts meth_lie `thenTc` \ (lie, lie_binds) ->
469 checkSigTyVars all_tyvars `thenTc` \ all_tyvars' ->
472 meth_tvs' = take (length meth_tvs) all_tyvars'
473 poly_meth_bind = AbsBinds meth_tvs'
474 (map instToId meth_dicts)
475 [(meth_tvs', meth_id, local_meth_id)]
476 emptyNameSet -- Inlines?
477 (lie_binds `andMonoBinds` meth_bind)
479 returnTc (poly_meth_bind, lie)
482 mkMethodBind :: InstOrigin
483 -> Class -> [TcType] -- Class and instance types
484 -> RenamedMonoBinds -- Method binding (pick the right one from in here)
486 -> TcM (Inst, -- Method inst
487 (Id, -- Global selector Id
488 TcSigInfo, -- Signature
489 RenamedMonoBinds)) -- Binding for the method
491 mkMethodBind origin clas inst_tys meth_binds (sel_id, dm_info)
492 = tcGetSrcLoc `thenNF_Tc` \ loc ->
493 newMethod origin sel_id inst_tys `thenNF_Tc` \ meth_inst ->
495 meth_id = instToId meth_inst
496 meth_name = idName meth_id
498 -- Figure out what method binding to use
499 -- If the user suppplied one, use it, else construct a default one
500 (case find_bind (idName sel_id) meth_name meth_binds of
501 Just user_bind -> returnTc user_bind
502 Nothing -> mkDefMethRhs origin clas inst_tys sel_id loc dm_info `thenTc` \ rhs ->
503 returnTc (FunMonoBind meth_name False -- Not infix decl
504 [mkSimpleMatch [] rhs placeHolderType loc] loc)
505 ) `thenTc` \ meth_bind ->
507 mkTcSig meth_id loc `thenNF_Tc` \ meth_sig ->
509 returnTc (meth_inst, (sel_id, meth_sig, meth_bind))
512 -- The user didn't supply a method binding,
513 -- so we have to make up a default binding
514 -- The RHS of a default method depends on the default-method info
515 mkDefMethRhs origin clas inst_tys sel_id loc (DefMeth dm_name)
516 = -- An polymorphic default method
517 returnTc (HsVar dm_name)
519 mkDefMethRhs origin clas inst_tys sel_id loc NoDefMeth
520 = -- No default method
521 -- Warn only if -fwarn-missing-methods
522 doptsTc Opt_WarnMissingMethods `thenNF_Tc` \ warn ->
523 warnTc (isInstDecl origin && warn)
524 (omittedMethodWarn sel_id) `thenNF_Tc_`
527 error_rhs = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID))
528 (HsLit (HsString (_PK_ error_msg)))
529 error_msg = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
532 mkDefMethRhs origin clas inst_tys sel_id loc GenDefMeth
533 = -- A generic default method
534 -- If the method is defined generically, we can only do the job if the
535 -- instance declaration is for a single-parameter type class with
536 -- a type constructor applied to type arguments in the instance decl
537 -- (checkTc, so False provokes the error)
538 checkTc (not (isInstDecl origin) || simple_inst)
539 (badGenericInstance sel_id) `thenTc_`
541 ioToTc (dumpIfSet opt_PprStyle_Debug "Generic RHS" stuff) `thenNF_Tc_`
544 rhs = mkGenericRhs sel_id clas_tyvar tycon
546 stuff = vcat [ppr clas <+> ppr inst_tys,
547 nest 4 (ppr sel_id <+> equals <+> ppr rhs)]
549 -- The tycon is only used in the generic case, and in that
550 -- case we require that the instance decl is for a single-parameter
551 -- type class with type variable arguments:
552 -- instance (...) => C (T a b)
553 simple_inst = maybeToBool maybe_tycon
554 clas_tyvar = head (classTyVars clas)
555 Just tycon = maybe_tycon
556 maybe_tycon = case inst_tys of
557 [ty] -> case tcSplitTyConApp_maybe ty of
558 Just (tycon, arg_tys) | all tcIsTyVarTy arg_tys -> Just tycon
562 isInstDecl InstanceDeclOrigin = True
563 isInstDecl ClassDeclOrigin = False
568 -- The renamer just puts the selector ID as the binder in the method binding
569 -- but we must use the method name; so we substitute it here. Crude but simple.
570 find_bind sel_name meth_name (FunMonoBind op_name fix matches loc)
571 | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
572 find_bind sel_name meth_name (AndMonoBinds b1 b2)
573 = find_bind sel_name meth_name b1 `seqMaybe` find_bind sel_name meth_name b2
574 find_bind sel_name meth_name other = Nothing -- Default case
576 -- Find the prags for this method, and replace the
577 -- selector name with the method name
578 find_prags sel_name meth_name [] = []
579 find_prags sel_name meth_name (SpecSig name ty loc : prags)
580 | name == sel_name = SpecSig meth_name ty loc : find_prags sel_name meth_name prags
581 find_prags sel_name meth_name (InlineSig sense name phase loc : prags)
582 | name == sel_name = InlineSig sense meth_name phase loc : find_prags sel_name meth_name prags
583 find_prags sel_name meth_name (prag:prags) = find_prags sel_name meth_name prags
591 = ptext SLIT("When checking the default methods for class") <+> quotes (ppr clas)
594 = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
597 = hsep [ptext SLIT("Class"), quotes (ppr clas),
598 ptext SLIT("does not have a method"), quotes (ppr op)]
600 omittedMethodWarn sel_id
601 = ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id)
603 badGenericInstance sel_id
604 = sep [ptext SLIT("Can't derive generic code for") <+> quotes (ppr sel_id),
605 ptext SLIT("because the instance declaration is not for a simple type (T a b c)"),
606 ptext SLIT("(where T is a derivable type constructor)")]
609 = ptext SLIT("Can't mix generic and non-generic equations for class method") <+> quotes (ppr op)