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, newDFunName
30 import TcInstUtil ( InstInfo(..), classDataCon )
31 import TcMonoType ( tcHsSigType )
32 import TcSimplify ( tcSimplifyAndCheck )
33 import TcType ( TcTyVar, zonkTcSigTyVars )
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 Maybes ( maybeToBool, catMaybes, expectJust )
42 import MkId ( mkDictFunId )
43 import Module ( Module )
44 import Name ( isLocallyDefined, NamedThing(..) )
45 import NameSet ( emptyNameSet )
46 import PrelInfo ( eRROR_ID )
47 import PprType ( pprConstraint )
48 import TyCon ( isSynTyCon, tyConDerivings )
49 import Type ( Type, isUnLiftedType, mkTyVarTys,
50 splitSigmaTy, isTyVarTy,
51 splitTyConApp_maybe, splitDictTy_maybe,
52 getClassTys_maybe, splitAlgTyConApp_maybe,
53 classesToPreds, classesOfPreds,
54 unUsgTy, tyVarsOfTypes
56 import Subst ( mkTopTyVarSubst, substClasses )
57 import VarSet ( mkVarSet, varSetElems )
58 import TysWiredIn ( stringTy, isFFIArgumentTy, isFFIResultTy )
59 import Unique ( Unique, cCallableClassKey, cReturnableClassKey, hasKey, Uniquable(..) )
63 Typechecking instance declarations is done in two passes. The first
64 pass, made by @tcInstDecls1@, collects information to be used in the
67 This pre-processed info includes the as-yet-unprocessed bindings
68 inside the instance declaration. These are type-checked in the second
69 pass, when the class-instance envs and GVE contain all the info from
70 all the instance and value decls. Indeed that's the reason we need
71 two passes over the instance decls.
74 Here is the overall algorithm.
75 Assume that we have an instance declaration
77 instance c => k (t tvs) where b
81 $LIE_c$ is the LIE for the context of class $c$
83 $betas_bar$ is the free variables in the class method type, excluding the
86 $LIE_cop$ is the LIE constraining a particular class method
88 $tau_cop$ is the tau type of a class method
90 $LIE_i$ is the LIE for the context of instance $i$
92 $X$ is the instance constructor tycon
94 $gammas_bar$ is the set of type variables of the instance
96 $LIE_iop$ is the LIE for a particular class method instance
98 $tau_iop$ is the tau type for this instance of a class method
100 $alpha$ is the class variable
102 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
104 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
107 ToDo: Update the list above with names actually in the code.
111 First, make the LIEs for the class and instance contexts, which means
112 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
113 and make LIElistI and LIEI.
115 Then process each method in turn.
117 order the instance methods according to the ordering of the class methods
119 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
121 Create final dictionary function from bindings generated already
123 df = lambda inst_tyvars
130 in <op1,op2,...,opn,sd1,...,sdm>
132 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
133 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
137 tcInstDecls1 :: ValueEnv -- Contains IdInfo for dfun ids
139 -> Module -- Module for deriving
140 -> FixityEnv -- For derivings
141 -> RnNameSupply -- For renaming derivings
142 -> TcM s (Bag InstInfo,
145 tcInstDecls1 unf_env decls mod fixs rn_name_supply
146 = -- Do the ordinary instance declarations
147 mapNF_Tc (tcInstDecl1 mod unf_env)
148 [inst_decl | InstD inst_decl <- decls] `thenNF_Tc` \ inst_info_bags ->
150 decl_inst_info = unionManyBags inst_info_bags
152 -- Handle "derived" instances; note that we only do derivings
153 -- for things in this module; we ignore deriving decls from
155 tcDeriving mod fixs rn_name_supply decl_inst_info
156 `thenTc` \ (deriv_inst_info, deriv_binds) ->
159 full_inst_info = deriv_inst_info `unionBags` decl_inst_info
161 returnTc (full_inst_info, deriv_binds)
164 tcInstDecl1 :: Module -> ValueEnv -> RenamedInstDecl -> NF_TcM s (Bag InstInfo)
166 tcInstDecl1 mod unf_env (InstDecl poly_ty binds uprags maybe_dfun_name src_loc)
167 = -- Prime error recovery, set source location
168 recoverNF_Tc (returnNF_Tc emptyBag) $
169 tcAddSrcLoc src_loc $
171 -- Type-check all the stuff before the "where"
172 tcHsSigType poly_ty `thenTc` \ poly_ty' ->
174 (tyvars, theta, dict_ty) = splitSigmaTy poly_ty'
175 constr = classesOfPreds theta
176 (clas, inst_tys) = case splitDictTy_maybe dict_ty of
178 Nothing -> pprPanic "tcInstDecl1" (ppr poly_ty)
181 (case maybe_dfun_name of
182 Nothing -> -- A source-file instance declaration
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 scrutiniseInstanceHead clas inst_tys `thenNF_Tc_`
190 mapNF_Tc scrutiniseInstanceConstraint constr `thenNF_Tc_`
192 -- Make the dfun id and return it
193 newDFunName mod clas inst_tys src_loc `thenNF_Tc` \ dfun_name ->
194 returnNF_Tc (mkDictFunId dfun_name clas tyvars inst_tys constr)
196 Just dfun_name -> -- An interface-file instance declaration
197 -- Make the dfun id and add info from interface file
199 dfun_id = mkDictFunId dfun_name clas tyvars inst_tys constr
201 returnNF_Tc (tcAddImportedIdInfo unf_env dfun_id)
202 ) `thenNF_Tc` \ dfun_id ->
204 returnTc (unitBag (InstInfo clas tyvars inst_tys constr dfun_id binds src_loc uprags))
208 %************************************************************************
210 \subsection{Type-checking instance declarations, pass 2}
212 %************************************************************************
215 tcInstDecls2 :: Bag InstInfo
216 -> NF_TcM s (LIE, TcMonoBinds)
218 tcInstDecls2 inst_decls
219 = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
221 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
222 tc2 `thenNF_Tc` \ (lie2, binds2) ->
223 returnNF_Tc (lie1 `plusLIE` lie2,
224 binds1 `AndMonoBinds` binds2)
228 ======= New documentation starts here (Sept 92) ==============
230 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
231 the dictionary function for this instance declaration. For example
233 instance Foo a => Foo [a] where
237 might generate something like
239 dfun.Foo.List dFoo_a = let op1 x = ...
245 HOWEVER, if the instance decl has no context, then it returns a
246 bigger @HsBinds@ with declarations for each method. For example
248 instance Foo [a] where
254 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
255 const.Foo.op1.List a x = ...
256 const.Foo.op2.List a y = ...
258 This group may be mutually recursive, because (for example) there may
259 be no method supplied for op2 in which case we'll get
261 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
263 that is, the default method applied to the dictionary at this type.
265 What we actually produce in either case is:
267 AbsBinds [a] [dfun_theta_dicts]
268 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
269 { d = (sd1,sd2, ..., op1, op2, ...)
274 The "maybe" says that we only ask AbsBinds to make global constant methods
275 if the dfun_theta is empty.
278 For an instance declaration, say,
280 instance (C1 a, C2 b) => C (T a b) where
283 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
284 function whose type is
286 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
288 Notice that we pass it the superclass dictionaries at the instance type; this
289 is the ``Mark Jones optimisation''. The stuff before the "=>" here
290 is the @dfun_theta@ below.
292 First comes the easy case of a non-local instance decl.
295 tcInstDecl2 :: InstInfo -> NF_TcM s (LIE, TcMonoBinds)
297 tcInstDecl2 (InstInfo clas inst_tyvars inst_tys
301 | not (isLocallyDefined dfun_id)
302 = returnNF_Tc (emptyLIE, EmptyMonoBinds)
305 = -- Prime error recovery
306 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
309 -- Check that all the method bindings come from this class
310 checkFromThisClass clas monobinds `thenNF_Tc_`
312 -- Instantiate the instance decl with tc-style type variables
313 tcInstId dfun_id `thenNF_Tc` \ (inst_tyvars', dfun_theta', dict_ty') ->
315 (clas, inst_tys') = expectJust "tcInstDecl2" (splitDictTy_maybe dict_ty')
317 origin = InstanceDeclOrigin
319 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
321 dm_ids = [dm_id | (_, dm_id, _) <- op_items]
323 -- Instantiate the theta found in the original instance decl
324 inst_decl_theta' = substClasses (mkTopTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars'))
327 -- Instantiate the super-class context with inst_tys
328 sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
330 -- Create dictionary Ids from the specified instance contexts.
331 newClassDicts origin sc_theta' `thenNF_Tc` \ (sc_dicts, sc_dict_ids) ->
332 newDicts origin dfun_theta' `thenNF_Tc` \ (dfun_arg_dicts, dfun_arg_dicts_ids) ->
333 newClassDicts origin inst_decl_theta' `thenNF_Tc` \ (inst_decl_dicts, _) ->
334 newClassDicts origin [(clas,inst_tys')] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
336 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
337 tcExtendGlobalValEnv dm_ids (
338 -- Default-method Ids may be mentioned in synthesised RHSs
340 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
341 (classesToPreds inst_decl_theta')
342 monobinds uprags True)
344 )) `thenTc` \ (method_binds_s, insts_needed_s, meth_lies_w_ids) ->
346 -- Deal with SPECIALISE instance pragmas by making them
347 -- look like SPECIALISE pragmas for the dfun
349 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
351 tcExtendGlobalValEnv [dfun_id] (
352 tcSpecSigs dfun_prags
353 ) `thenTc` \ (prag_binds, prag_lie) ->
355 -- Check the overloading constraints of the methods and superclasses
357 -- tcMethodBind has checked that the class_tyvars havn't
358 -- been unified with each other or another type, but we must
359 -- still zonk them before passing them to tcSimplifyAndCheck
360 zonkTcSigTyVars inst_tyvars' `thenNF_Tc` \ zonked_inst_tyvars ->
362 inst_tyvars_set = mkVarSet zonked_inst_tyvars
364 (meth_lies, meth_ids) = unzip meth_lies_w_ids
366 -- These insts are in scope; quite a few, eh?
367 avail_insts = this_dict `plusLIE`
368 dfun_arg_dicts `plusLIE`
370 unionManyBags meth_lies
372 methods_lie = plusLIEs insts_needed_s
375 -- Ditto method bindings
376 tcAddErrCtxt methodCtxt (
378 (ptext SLIT("instance declaration context"))
379 inst_tyvars_set -- Local tyvars
382 ) `thenTc` \ (const_lie1, lie_binds1) ->
384 -- Check that we *could* construct the superclass dictionaries,
385 -- even though we are *actually* going to pass the superclass dicts in;
386 -- the check ensures that the caller will never have
387 --a problem building them.
388 tcAddErrCtxt superClassCtxt (
390 (ptext SLIT("instance declaration context"))
391 inst_tyvars_set -- Local tyvars
392 inst_decl_dicts -- The instance dictionaries available
393 sc_dicts -- The superclass dicationaries reqd
395 -- Ignore the result; we're only doing
396 -- this to make sure it can be done.
398 -- Now do the simplification again, this time to get the
399 -- bindings; this time we use an enhanced "avails"
400 -- Ignore errors because they come from the *previous* tcSimplify
403 (ptext SLIT("instance declaration context"))
405 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
406 -- get bound by just selecting from this_dict!!
408 ) `thenTc` \ (const_lie2, lie_binds2) ->
411 -- Create the result bindings
413 dict_constr = classDataCon clas
414 scs_and_meths = sc_dict_ids ++ meth_ids
418 = -- Blatant special case for CCallable, CReturnable
419 -- If the dictionary is empty then we should never
420 -- select anything from it, so we make its RHS just
421 -- emit an error message. This in turn means that we don't
422 -- mention the constructor, which doesn't exist for CCallable, CReturnable
423 -- Hardly beautiful, but only three extra lines.
424 HsApp (TyApp (HsVar eRROR_ID) [(unUsgTy . idType) this_dict_id])
425 (HsLitOut (HsString msg) stringTy)
427 | otherwise -- The common case
428 = mkHsConApp dict_constr inst_tys' (map HsVar (sc_dict_ids ++ meth_ids))
429 -- We don't produce a binding for the dict_constr; instead we
430 -- rely on the simplifier to unfold this saturated application
431 -- We do this rather than generate an HsCon directly, because
432 -- it means that the special cases (e.g. dictionary with only one
433 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
434 -- than needing to be repeated here.
437 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
439 dict_bind = VarMonoBind this_dict_id dict_rhs
440 method_binds = andMonoBindList method_binds_s
446 [(inst_tyvars', dfun_id, this_dict_id)]
447 emptyNameSet -- No inlines (yet)
448 (lie_binds1 `AndMonoBinds`
449 lie_binds2 `AndMonoBinds`
450 method_binds `AndMonoBinds`
453 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
454 main_bind `AndMonoBinds` prag_binds)
458 %************************************************************************
460 \subsection{Checking for a decent instance type}
462 %************************************************************************
464 @scrutiniseInstanceHead@ checks the type {\em and} its syntactic constraints:
465 it must normally look like: @instance Foo (Tycon a b c ...) ...@
467 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
468 flag is on, or (2)~the instance is imported (they must have been
469 compiled elsewhere). In these cases, we let them go through anyway.
471 We can also have instances for functions: @instance Foo (a -> b) ...@.
474 scrutiniseInstanceConstraint (clas, tys)
476 || opt_AllowUndecidableInstances = returnNF_Tc ()
477 | otherwise = addErrTc (instConstraintErr clas tys)
479 scrutiniseInstanceHead clas inst_taus
481 -- A user declaration of a CCallable/CReturnable instance
482 -- must be for a "boxed primitive" type.
483 (clas `hasKey` cCallableClassKey && not (ccallable_type first_inst_tau)) ||
484 (clas `hasKey` cReturnableClassKey && not (creturnable_type first_inst_tau))
485 = addErrTc (nonBoxedPrimCCallErr clas first_inst_tau)
488 -- It is obviously illegal to have an explicit instance
489 -- for something that we are also planning to `derive'
490 | maybeToBool alg_tycon_app_maybe && clas `elem` (tyConDerivings alg_tycon)
491 = addErrTc (derivingWhenInstanceExistsErr clas first_inst_tau)
492 -- Kind check will have ensured inst_taus is of length 1
494 -- Allow anything for AllowUndecidableInstances
495 | opt_AllowUndecidableInstances
498 -- If GlasgowExts then check at least one isn't a type variable
500 = if all isTyVarTy inst_taus then
501 addErrTc (instTypeErr clas inst_taus (text "There must be at least one non-type-variable in the instance head"))
505 -- WITH HASKELL 1.4, MUST HAVE C (T a b c)
506 | not (length inst_taus == 1 &&
507 maybeToBool maybe_tycon_app && -- Yes, there's a type constuctor
508 not (isSynTyCon tycon) && -- ...but not a synonym
509 all isTyVarTy arg_tys && -- Applied to type variables
510 length (varSetElems (tyVarsOfTypes arg_tys)) == length arg_tys
511 -- This last condition checks that all the type variables are distinct
513 = addErrTc (instTypeErr clas inst_taus
514 (text "the instance type must be of form (T a b c)" $$
515 text "where T is not a synonym, and a,b,c are distinct type variables")
522 (first_inst_tau : _) = inst_taus
524 -- Stuff for algebraic or -> type
525 maybe_tycon_app = splitTyConApp_maybe first_inst_tau
526 Just (tycon, arg_tys) = maybe_tycon_app
528 -- Stuff for an *algebraic* data type
529 alg_tycon_app_maybe = splitAlgTyConApp_maybe first_inst_tau
530 -- The "Alg" part looks through synonyms
531 Just (alg_tycon, _, _) = alg_tycon_app_maybe
533 ccallable_type ty = isFFIArgumentTy False {- Not safe call -} ty
534 creturnable_type ty = isFFIResultTy ty
538 instConstraintErr clas tys
539 = hang (ptext SLIT("Illegal constraint") <+>
540 quotes (pprConstraint clas tys) <+>
541 ptext SLIT("in instance context"))
542 4 (ptext SLIT("(Instance contexts must constrain only type variables)"))
544 instTypeErr clas tys msg
545 = sep [ptext SLIT("Illegal instance declaration for") <+> quotes (pprConstraint clas tys),
549 derivingWhenInstanceExistsErr clas tycon
550 = hang (hsep [ptext SLIT("Deriving class"),
552 ptext SLIT("type"), quotes (ppr tycon)])
553 4 (ptext SLIT("when an explicit instance exists"))
555 nonBoxedPrimCCallErr clas inst_ty
556 = hang (ptext SLIT("Unacceptable instance type for ccall-ish class"))
557 4 (hsep [ ptext SLIT("class"), ppr clas, ptext SLIT("type"),
560 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
561 superClassCtxt = ptext SLIT("When checking the superclasses of an instance declaration")