2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcInstDecls]{Typechecking instance declarations}
7 module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
9 #include "HsVersions.h"
11 import HsSyn ( HsDecl(..), InstDecl(..),
12 HsBinds(..), MonoBinds(..),
13 HsExpr(..), InPat(..), HsLit(..), Sig(..),
16 import RnHsSyn ( RenamedHsBinds, RenamedInstDecl, RenamedHsDecl )
17 import TcHsSyn ( TcMonoBinds, mkHsConApp )
19 import TcBinds ( tcSpecSigs )
20 import TcClassDcl ( tcMethodBind, checkFromThisClass )
22 import RnMonad ( RnNameSupply, FixityEnv )
23 import Inst ( Inst, InstOrigin(..),
24 newDicts, newClassDicts,
25 LIE, emptyLIE, plusLIE, plusLIEs )
26 import TcDeriv ( tcDeriving )
27 import TcEnv ( ValueEnv, tcExtendGlobalValEnv, tcExtendTyVarEnvForMeths,
28 tcAddImportedIdInfo, tcInstId
30 import TcInstUtil ( InstInfo(..), classDataCon )
31 import TcMonoType ( tcHsTopType )
32 import TcSimplify ( tcSimplifyAndCheck )
33 import TcType ( TcTyVar, zonkTcTyVarBndr )
35 import Bag ( emptyBag, unitBag, unionBags, unionManyBags,
38 import CmdLineOpts ( opt_GlasgowExts, opt_AllowUndecidableInstances )
39 import Class ( classBigSig, Class )
40 import Var ( idName, idType, Id, TyVar )
41 import DataCon ( isNullaryDataCon, splitProductType_maybe )
42 import Maybes ( maybeToBool, catMaybes, expectJust )
43 import MkId ( mkDictFunId )
44 import Module ( ModuleName )
45 import Name ( isLocallyDefined, NamedThing(..) )
46 import NameSet ( emptyNameSet )
47 import PrelInfo ( eRROR_ID )
48 import PprType ( pprConstraint )
49 import SrcLoc ( SrcLoc )
50 import TyCon ( isSynTyCon, tyConDerivings )
51 import Type ( Type, isUnLiftedType, mkTyVarTys,
52 splitSigmaTy, isTyVarTy,
53 splitTyConApp_maybe, splitDictTy_maybe,
54 getClassTys_maybe, splitAlgTyConApp_maybe,
55 classesToPreds, classesOfPreds,
56 unUsgTy, tyVarsOfTypes
58 import Subst ( mkTopTyVarSubst, substClasses )
59 import VarSet ( mkVarSet, varSetElems )
60 import TysPrim ( byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
61 import TysWiredIn ( stringTy, isFFIArgumentTy, isFFIResultTy )
62 import Unique ( Unique, cCallableClassKey, cReturnableClassKey, hasKey, Uniquable(..) )
66 Typechecking instance declarations is done in two passes. The first
67 pass, made by @tcInstDecls1@, collects information to be used in the
70 This pre-processed info includes the as-yet-unprocessed bindings
71 inside the instance declaration. These are type-checked in the second
72 pass, when the class-instance envs and GVE contain all the info from
73 all the instance and value decls. Indeed that's the reason we need
74 two passes over the instance decls.
77 Here is the overall algorithm.
78 Assume that we have an instance declaration
80 instance c => k (t tvs) where b
84 $LIE_c$ is the LIE for the context of class $c$
86 $betas_bar$ is the free variables in the class method type, excluding the
89 $LIE_cop$ is the LIE constraining a particular class method
91 $tau_cop$ is the tau type of a class method
93 $LIE_i$ is the LIE for the context of instance $i$
95 $X$ is the instance constructor tycon
97 $gammas_bar$ is the set of type variables of the instance
99 $LIE_iop$ is the LIE for a particular class method instance
101 $tau_iop$ is the tau type for this instance of a class method
103 $alpha$ is the class variable
105 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
107 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
110 ToDo: Update the list above with names actually in the code.
114 First, make the LIEs for the class and instance contexts, which means
115 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
116 and make LIElistI and LIEI.
118 Then process each method in turn.
120 order the instance methods according to the ordering of the class methods
122 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
124 Create final dictionary function from bindings generated already
126 df = lambda inst_tyvars
133 in <op1,op2,...,opn,sd1,...,sdm>
135 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
136 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
140 tcInstDecls1 :: ValueEnv -- Contains IdInfo for dfun ids
142 -> ModuleName -- module name for deriving
144 -> RnNameSupply -- for renaming derivings
145 -> TcM s (Bag InstInfo,
148 tcInstDecls1 unf_env decls mod_name fixs rn_name_supply
149 = -- Do the ordinary instance declarations
150 mapNF_Tc (tcInstDecl1 unf_env)
151 [inst_decl | InstD inst_decl <- decls] `thenNF_Tc` \ inst_info_bags ->
153 decl_inst_info = unionManyBags inst_info_bags
155 -- Handle "derived" instances; note that we only do derivings
156 -- for things in this module; we ignore deriving decls from
158 tcDeriving mod_name fixs rn_name_supply decl_inst_info
159 `thenTc` \ (deriv_inst_info, deriv_binds) ->
162 full_inst_info = deriv_inst_info `unionBags` decl_inst_info
164 returnTc (full_inst_info, deriv_binds)
167 tcInstDecl1 :: ValueEnv -> RenamedInstDecl -> NF_TcM s (Bag InstInfo)
169 tcInstDecl1 unf_env (InstDecl poly_ty binds uprags dfun_name src_loc)
170 = -- Prime error recovery, set source location
171 recoverNF_Tc (returnNF_Tc emptyBag) $
172 tcAddSrcLoc src_loc $
174 -- Type-check all the stuff before the "where"
175 tcHsTopType poly_ty `thenTc` \ poly_ty' ->
177 (tyvars, theta, dict_ty) = splitSigmaTy poly_ty'
178 constr = classesOfPreds theta
179 (clas, inst_tys) = case splitDictTy_maybe dict_ty of
181 Nothing -> pprPanic "tcInstDecl1" (ppr poly_ty)
184 -- Check for respectable instance type, and context
185 -- but only do this for non-imported instance decls.
186 -- Imported ones should have been checked already, and may indeed
187 -- contain something illegal in normal Haskell, notably
188 -- instance CCallable [Char]
189 (if isLocallyDefined dfun_name then
190 scrutiniseInstanceHead clas inst_tys `thenNF_Tc_`
191 mapNF_Tc scrutiniseInstanceConstraint constr
198 dfun_id = mkDictFunId dfun_name clas tyvars inst_tys constr
200 -- Add info from interface file
201 final_dfun_id = tcAddImportedIdInfo unf_env dfun_id
203 returnTc (unitBag (InstInfo clas tyvars inst_tys constr
205 binds src_loc uprags))
209 %************************************************************************
211 \subsection{Type-checking instance declarations, pass 2}
213 %************************************************************************
216 tcInstDecls2 :: Bag InstInfo
217 -> NF_TcM s (LIE, TcMonoBinds)
219 tcInstDecls2 inst_decls
220 = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
222 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
223 tc2 `thenNF_Tc` \ (lie2, binds2) ->
224 returnNF_Tc (lie1 `plusLIE` lie2,
225 binds1 `AndMonoBinds` binds2)
229 ======= New documentation starts here (Sept 92) ==============
231 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
232 the dictionary function for this instance declaration. For example
234 instance Foo a => Foo [a] where
238 might generate something like
240 dfun.Foo.List dFoo_a = let op1 x = ...
246 HOWEVER, if the instance decl has no context, then it returns a
247 bigger @HsBinds@ with declarations for each method. For example
249 instance Foo [a] where
255 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
256 const.Foo.op1.List a x = ...
257 const.Foo.op2.List a y = ...
259 This group may be mutually recursive, because (for example) there may
260 be no method supplied for op2 in which case we'll get
262 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
264 that is, the default method applied to the dictionary at this type.
266 What we actually produce in either case is:
268 AbsBinds [a] [dfun_theta_dicts]
269 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
270 { d = (sd1,sd2, ..., op1, op2, ...)
275 The "maybe" says that we only ask AbsBinds to make global constant methods
276 if the dfun_theta is empty.
279 For an instance declaration, say,
281 instance (C1 a, C2 b) => C (T a b) where
284 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
285 function whose type is
287 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
289 Notice that we pass it the superclass dictionaries at the instance type; this
290 is the ``Mark Jones optimisation''. The stuff before the "=>" here
291 is the @dfun_theta@ below.
293 First comes the easy case of a non-local instance decl.
296 tcInstDecl2 :: InstInfo -> NF_TcM s (LIE, TcMonoBinds)
298 tcInstDecl2 (InstInfo clas inst_tyvars inst_tys
302 | not (isLocallyDefined dfun_id)
303 = returnNF_Tc (emptyLIE, EmptyMonoBinds)
306 -- I deleted this "optimisation" because when importing these
307 -- instance decls the renamer would look for the dfun bindings and they weren't there.
308 -- This would be fixable, but it seems simpler just to produce a tiny void binding instead,
309 -- even though it's never used.
311 -- This case deals with CCallable etc, which don't need any bindings
313 = returnNF_Tc (emptyLIE, EmptyBinds)
317 = -- Prime error recovery
318 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
321 -- Instantiate the instance decl with tc-style type variables
322 tcInstId dfun_id `thenNF_Tc` \ (inst_tyvars', dfun_theta', dict_ty') ->
324 (clas, inst_tys') = expectJust "tcInstDecl2" (splitDictTy_maybe dict_ty')
326 origin = InstanceDeclOrigin
328 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
330 dm_ids = [dm_id | (_, dm_id, _) <- op_items]
332 -- Instantiate the theta found in the original instance decl
333 inst_decl_theta' = substClasses (mkTopTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars'))
336 -- Instantiate the super-class context with inst_tys
337 sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
339 -- Create dictionary Ids from the specified instance contexts.
340 newClassDicts origin sc_theta' `thenNF_Tc` \ (sc_dicts, sc_dict_ids) ->
341 newDicts origin dfun_theta' `thenNF_Tc` \ (dfun_arg_dicts, dfun_arg_dicts_ids) ->
342 newClassDicts origin inst_decl_theta' `thenNF_Tc` \ (inst_decl_dicts, _) ->
343 newClassDicts origin [(clas,inst_tys')] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
345 -- Check that all the method bindings come from this class
346 checkFromThisClass clas op_items monobinds `thenNF_Tc_`
348 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
349 tcExtendGlobalValEnv dm_ids (
350 -- Default-method Ids may be mentioned in synthesised RHSs
352 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
353 (classesToPreds inst_decl_theta')
354 monobinds uprags True)
356 )) `thenTc` \ (method_binds_s, insts_needed_s, meth_lies_w_ids) ->
358 -- Deal with SPECIALISE instance pragmas by making them
359 -- look like SPECIALISE pragmas for the dfun
361 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
363 tcExtendGlobalValEnv [dfun_id] (
364 tcSpecSigs dfun_prags
365 ) `thenTc` \ (prag_binds, prag_lie) ->
367 -- Check the overloading constraints of the methods and superclasses
369 -- tcMethodBind has checked that the class_tyvars havn't
370 -- been unified with each other or another type, but we must
372 mapNF_Tc zonkTcTyVarBndr inst_tyvars' `thenNF_Tc` \ zonked_inst_tyvars ->
374 inst_tyvars_set = mkVarSet zonked_inst_tyvars
376 (meth_lies, meth_ids) = unzip meth_lies_w_ids
378 -- These insts are in scope; quite a few, eh?
379 avail_insts = this_dict `plusLIE`
380 dfun_arg_dicts `plusLIE`
382 unionManyBags meth_lies
384 methods_lie = plusLIEs insts_needed_s
387 -- Ditto method bindings
388 tcAddErrCtxt methodCtxt (
390 (ptext SLIT("instance declaration context"))
391 inst_tyvars_set -- Local tyvars
394 ) `thenTc` \ (const_lie1, lie_binds1) ->
396 -- Check that we *could* construct the superclass dictionaries,
397 -- even though we are *actually* going to pass the superclass dicts in;
398 -- the check ensures that the caller will never have
399 --a problem building them.
400 tcAddErrCtxt superClassCtxt (
402 (ptext SLIT("instance declaration context"))
403 inst_tyvars_set -- Local tyvars
404 inst_decl_dicts -- The instance dictionaries available
405 sc_dicts -- The superclass dicationaries reqd
407 -- Ignore the result; we're only doing
408 -- this to make sure it can be done.
410 -- Now do the simplification again, this time to get the
411 -- bindings; this time we use an enhanced "avails"
412 -- Ignore errors because they come from the *previous* tcSimplify
415 (ptext SLIT("instance declaration context"))
417 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
418 -- get bound by just selecting from this_dict!!
420 ) `thenTc` \ (const_lie2, lie_binds2) ->
423 -- Create the result bindings
425 dict_constr = classDataCon clas
426 scs_and_meths = sc_dict_ids ++ meth_ids
430 = -- Blatant special case for CCallable, CReturnable
431 -- If the dictionary is empty then we should never
432 -- select anything from it, so we make its RHS just
433 -- emit an error message. This in turn means that we don't
434 -- mention the constructor, which doesn't exist for CCallable, CReturnable
435 -- Hardly beautiful, but only three extra lines.
436 HsApp (TyApp (HsVar eRROR_ID) [(unUsgTy . idType) this_dict_id])
437 (HsLitOut (HsString msg) stringTy)
439 | otherwise -- The common case
440 = mkHsConApp dict_constr inst_tys' (map HsVar (sc_dict_ids ++ meth_ids))
441 -- We don't produce a binding for the dict_constr; instead we
442 -- rely on the simplifier to unfold this saturated application
443 -- We do this rather than generate an HsCon directly, because
444 -- it means that the special cases (e.g. dictionary with only one
445 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
446 -- than needing to be repeated here.
449 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
451 dict_bind = VarMonoBind this_dict_id dict_rhs
452 method_binds = andMonoBindList method_binds_s
458 [(inst_tyvars', dfun_id, this_dict_id)]
459 emptyNameSet -- No inlines (yet)
460 (lie_binds1 `AndMonoBinds`
461 lie_binds2 `AndMonoBinds`
462 method_binds `AndMonoBinds`
465 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
466 main_bind `AndMonoBinds` prag_binds)
470 %************************************************************************
472 \subsection{Checking for a decent instance type}
474 %************************************************************************
476 @scrutiniseInstanceHead@ checks the type {\em and} its syntactic constraints:
477 it must normally look like: @instance Foo (Tycon a b c ...) ...@
479 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
480 flag is on, or (2)~the instance is imported (they must have been
481 compiled elsewhere). In these cases, we let them go through anyway.
483 We can also have instances for functions: @instance Foo (a -> b) ...@.
486 scrutiniseInstanceConstraint (clas, tys)
488 || opt_AllowUndecidableInstances = returnNF_Tc ()
489 | otherwise = addErrTc (instConstraintErr clas tys)
491 scrutiniseInstanceHead clas inst_taus
493 -- A user declaration of a CCallable/CReturnable instance
494 -- must be for a "boxed primitive" type.
495 (clas `hasKey` cCallableClassKey && not (ccallable_type first_inst_tau)) ||
496 (clas `hasKey` cReturnableClassKey && not (creturnable_type first_inst_tau))
497 = addErrTc (nonBoxedPrimCCallErr clas first_inst_tau)
500 -- It is obviously illegal to have an explicit instance
501 -- for something that we are also planning to `derive'
502 | maybeToBool alg_tycon_app_maybe && clas `elem` (tyConDerivings alg_tycon)
503 = addErrTc (derivingWhenInstanceExistsErr clas first_inst_tau)
504 -- Kind check will have ensured inst_taus is of length 1
506 -- Allow anything for AllowUndecidableInstances
507 | opt_AllowUndecidableInstances
510 -- If GlasgowExts then check at least one isn't a type variable
512 = if all isTyVarTy inst_taus then
513 addErrTc (instTypeErr clas inst_taus (text "There must be at least one non-type-variable in the instance head"))
517 -- WITH HASKELL 1.4, MUST HAVE C (T a b c)
518 | not (length inst_taus == 1 &&
519 maybeToBool maybe_tycon_app && -- Yes, there's a type constuctor
520 not (isSynTyCon tycon) && -- ...but not a synonym
521 all isTyVarTy arg_tys && -- Applied to type variables
522 length (varSetElems (tyVarsOfTypes arg_tys)) == length arg_tys
523 -- This last condition checks that all the type variables are distinct
525 = addErrTc (instTypeErr clas inst_taus
526 (text "the instance type must be of form (T a b c)" $$
527 text "where T is not a synonym, and a,b,c are distinct type variables")
534 (first_inst_tau : _) = inst_taus
536 -- Stuff for algebraic or -> type
537 maybe_tycon_app = splitTyConApp_maybe first_inst_tau
538 Just (tycon, arg_tys) = maybe_tycon_app
540 -- Stuff for an *algebraic* data type
541 alg_tycon_app_maybe = splitAlgTyConApp_maybe first_inst_tau
542 -- The "Alg" part looks through synonyms
543 Just (alg_tycon, _, _) = alg_tycon_app_maybe
545 ccallable_type ty = isFFIArgumentTy False {- Not safe call -} ty
546 creturnable_type ty = isFFIResultTy ty
550 instConstraintErr clas tys
551 = hang (ptext SLIT("Illegal constraint") <+>
552 quotes (pprConstraint clas tys) <+>
553 ptext SLIT("in instance context"))
554 4 (ptext SLIT("(Instance contexts must constrain only type variables)"))
556 instTypeErr clas tys msg
557 = sep [ptext SLIT("Illegal instance declaration for") <+> quotes (pprConstraint clas tys),
561 derivingWhenInstanceExistsErr clas tycon
562 = hang (hsep [ptext SLIT("Deriving class"),
564 ptext SLIT("type"), quotes (ppr tycon)])
565 4 (ptext SLIT("when an explicit instance exists"))
567 nonBoxedPrimCCallErr clas inst_ty
568 = hang (ptext SLIT("Unacceptable instance type for ccall-ish class"))
569 4 (hsep [ ptext SLIT("class"), ppr clas, ptext SLIT("type"),
572 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
573 superClassCtxt = ptext SLIT("When checking the superclasses of an instance declaration")