2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcInstDecls]{Typechecking instance declarations}
7 module TcInstDcls ( tcInstDecls1, tcInstDecls2, tcAddDeclCtxt ) where
9 #include "HsVersions.h"
12 import CmdLineOpts ( opt_GlasgowExts, opt_AllowUndecidableInstances, opt_D_dump_deriv )
14 import HsSyn ( HsDecl(..), InstDecl(..), TyClDecl(..),
15 MonoBinds(..), HsExpr(..), HsLit(..), Sig(..),
16 andMonoBindList, collectMonoBinders, isClassDecl
18 import HsTypes ( HsType (..), HsTyVarBndr(..), toHsTyVar )
19 import HsPat ( InPat (..) )
20 import HsMatches ( Match (..) )
21 import RnHsSyn ( RenamedHsBinds, RenamedInstDecl, RenamedHsDecl, extractHsTyVars )
22 import TcHsSyn ( TcMonoBinds, mkHsConApp )
23 import TcBinds ( tcSpecSigs )
24 import TcClassDcl ( tcMethodBind, badMethodErr )
26 import RnMonad ( RnNameSupply, FixityEnv )
27 import Inst ( InstOrigin(..),
28 newDicts, newClassDicts,
29 LIE, emptyLIE, plusLIE, plusLIEs )
30 import TcDeriv ( tcDeriving )
31 import TcEnv ( ValueEnv, tcExtendGlobalValEnv,
32 tcExtendTyVarEnvForMeths, TyThing (..),
33 tcAddImportedIdInfo, tcInstId, tcLookupClass,
34 newDFunName, tcExtendTyVarEnv
36 import TcInstUtil ( InstInfo(..), pprInstInfo, classDataCon, simpleInstInfoTyCon, simpleInstInfoTy )
37 import TcMonoType ( tcTyVars, tcHsSigType, tcHsType, kcHsSigType )
38 import TcSimplify ( tcSimplifyAndCheck )
39 import TcType ( zonkTcSigTyVars )
41 import Bag ( emptyBag, unitBag, unionBags, unionManyBags,
42 foldBag, Bag, listToBag
44 import Class ( Class, DefMeth(..), classBigSig )
45 import Var ( idName, idType )
46 import Maybes ( maybeToBool, expectJust )
47 import MkId ( mkDictFunId )
48 import Generics ( validGenericInstanceType )
49 import Module ( Module )
50 import Name ( isLocallyDefined )
51 import NameSet ( emptyNameSet, nameSetToList )
52 import PrelInfo ( eRROR_ID )
53 import PprType ( pprConstraint, pprPred )
54 import TyCon ( isSynTyCon, tyConDerivings )
55 import Type ( mkTyVarTys, splitSigmaTy, isTyVarTy,
56 splitTyConApp_maybe, splitDictTy_maybe,
57 splitAlgTyConApp_maybe, classesToPreds, classesOfPreds,
58 unUsgTy, tyVarsOfTypes, mkClassPred, mkTyVarTy,
61 import Subst ( mkTopTyVarSubst, substClasses, substTheta )
62 import VarSet ( mkVarSet, varSetElems )
63 import TysWiredIn ( genericTyCons, isFFIArgumentTy, isFFIResultTy )
64 import PrelNames ( cCallableClassKey, cReturnableClassKey, hasKey )
65 import Name ( Name, NameEnv, extendNameEnv_C, emptyNameEnv,
66 plusNameEnv_C, nameEnvElts )
67 import FiniteMap ( mapFM )
68 import SrcLoc ( SrcLoc )
69 import RnHsSyn -- ( RenamedMonoBinds )
70 import VarSet ( varSetElems )
71 import UniqFM ( mapUFM )
72 import Unique ( Uniquable(..) )
73 import BasicTypes ( NewOrData(..) )
74 import ErrUtils ( dumpIfSet )
75 import ListSetOps ( Assoc, emptyAssoc, plusAssoc_C, mapAssoc,
76 assocElts, extendAssoc_C,
77 equivClassesByUniq, minusList
79 import List ( intersect, (\\) )
83 Typechecking instance declarations is done in two passes. The first
84 pass, made by @tcInstDecls1@, collects information to be used in the
87 This pre-processed info includes the as-yet-unprocessed bindings
88 inside the instance declaration. These are type-checked in the second
89 pass, when the class-instance envs and GVE contain all the info from
90 all the instance and value decls. Indeed that's the reason we need
91 two passes over the instance decls.
94 Here is the overall algorithm.
95 Assume that we have an instance declaration
97 instance c => k (t tvs) where b
101 $LIE_c$ is the LIE for the context of class $c$
103 $betas_bar$ is the free variables in the class method type, excluding the
106 $LIE_cop$ is the LIE constraining a particular class method
108 $tau_cop$ is the tau type of a class method
110 $LIE_i$ is the LIE for the context of instance $i$
112 $X$ is the instance constructor tycon
114 $gammas_bar$ is the set of type variables of the instance
116 $LIE_iop$ is the LIE for a particular class method instance
118 $tau_iop$ is the tau type for this instance of a class method
120 $alpha$ is the class variable
122 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
124 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
127 ToDo: Update the list above with names actually in the code.
131 First, make the LIEs for the class and instance contexts, which means
132 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
133 and make LIElistI and LIEI.
135 Then process each method in turn.
137 order the instance methods according to the ordering of the class methods
139 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
141 Create final dictionary function from bindings generated already
143 df = lambda inst_tyvars
150 in <op1,op2,...,opn,sd1,...,sdm>
152 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
153 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
157 %************************************************************************
159 \subsection{Extracting instance decls}
161 %************************************************************************
163 Gather up the instance declarations from their various sources
166 tcInstDecls1 :: PersistentCompilerState
167 -> HomeSymbolTable -- Contains instances
168 -> TcEnv -- Contains IdInfo for dfun ids
169 -> Module -- Module for deriving
171 -> TcM (PersistentCompilerState, InstEnv, [InstInfo], RenamedHsBinds)
173 tcInstDecls1 pcs hst unf_env this_mod decls mod
175 inst_decls = [inst_decl | InstD inst_decl <- decls]
176 clas_decls = [clas_decl | TyClD clas_decl <- decls, isClassDecl cl_decl]
178 -- (1) Do the ordinary instance declarations
179 mapNF_Tc (tcInstDecl1 mod) inst_decls `thenNF_Tc` \ inst_infos ->
181 -- (2) Instances from generic class declarations
182 getGenericInstances mod clas_decls `thenTc` \ generic_inst_info ->
184 -- Next, consruct the instance environment so far, consisting of
185 -- a) cached non-home-package InstEnv (gotten from pcs) pcsInsts pcs
186 -- b) imported instance decls (not in the home package) inst_env1
187 -- c) other modules in this package (gotten from hst) inst_env2
188 -- d) local instance decls inst_env3
189 -- e) generic instances inst_env4
190 -- The result of (b) replaces the cached InstEnv in the PCS
192 (local_inst_info, imported_inst_info) = partition isLocalInst (concat inst_infos)
193 generic_inst_info = concat generic_inst_infos -- All local
195 imported_dfuns = map (tcAddImportedIdInfo unf_env . instInfoDFun) imported_inst_info
196 hst_dfuns = foldModuleEnv ((++) . md_insts) [] hst
198 addInstDFuns (pcsInsts pcs) imported_dfuns `thenNF_Tc` \ inst_env1 ->
199 addInstDFuns inst_env1 hst_dfuns `thenNF_Tc` \ inst_env2 ->
200 addInstInfos inst_env2 local_inst_info `thenNF_Tc` \ inst_env3 ->
201 addInstInfos inst_env3 generic_inst_info `thenNF_Tc` \ inst_env4 ->
204 -- (3) Compute instances from "deriving" clauses;
205 -- note that we only do derivings for things in this module;
206 -- we ignore deriving decls from interfaces!
207 -- This stuff computes a context for the derived instance decl, so it
208 -- needs to know about all the instances possible; hecne inst_env4
209 tcDeriving (pcsPRS pcs) this_mod inst_env4 local_tycons `thenTc` \ (deriv_inst_info, deriv_binds) ->
210 addInstInfos inst_env4 deriv_inst_info `thenNF_Tc` \ final_inst_env ->
212 returnTc (pcs { pcsInsts = inst_env1 },
214 generic_inst_info ++ deriv_inst_info ++ local_inst_info,
217 addInstInfos :: InstEnv -> [InstInfo] -> NF_TcM InstEnv
218 addInstInfos inst_env infos = addInstDfuns inst_env (map iDFun infos)
220 addInstDFuns :: InstEnv -> [DFunId] -> NF_TcM InstEnv
221 addInstDFuns dfuns infos
222 = addErrsTc errs `thenNF_Tc_`
225 (inst_env', errs) = extendInstEnv env dfuns
229 tcInstDecl1 :: Module -> ValueEnv -> RenamedInstDecl -> NF_TcM [InstInfo]
230 -- Deal with a single instance declaration
231 tcInstDecl1 mod unf_env (InstDecl poly_ty binds uprags maybe_dfun_name src_loc)
232 = -- Prime error recovery, set source location
233 recoverNF_Tc (returnNF_Tc []) $
234 tcAddSrcLoc src_loc $
236 -- Type-check all the stuff before the "where"
237 tcHsSigType poly_ty `thenTc` \ poly_ty' ->
239 (tyvars, theta, dict_ty) = splitSigmaTy poly_ty'
240 (clas, inst_tys) = case splitDictTy_maybe dict_ty of
242 Nothing -> pprPanic "tcInstDecl1" (ppr poly_ty)
245 (case maybe_dfun_name of
246 Nothing -> -- A source-file instance declaration
248 -- Check for respectable instance type, and context
249 -- but only do this for non-imported instance decls.
250 -- Imported ones should have been checked already, and may indeed
251 -- contain something illegal in normal Haskell, notably
252 -- instance CCallable [Char]
253 scrutiniseInstanceHead clas inst_tys `thenNF_Tc_`
254 mapNF_Tc scrutiniseInstanceConstraint theta `thenNF_Tc_`
256 -- Make the dfun id and return it
257 newDFunName mod clas inst_tys src_loc `thenNF_Tc` \ dfun_name ->
258 returnNF_Tc (True, mkDictFunId dfun_name clas tyvars inst_tys theta)
260 Just dfun_name -> -- An interface-file instance declaration
262 returnNF_Tc (False, mkDictFunId dfun_name clas tyvars inst_tys theta)
263 ) `thenNF_Tc` \ (is_local, dfun_id) ->
265 returnTc [InstInfo { iLocal = is_local,
266 iClass = clas, iTyVars = tyvars, iTys = inst_tys,
267 iTheta = theta, iDFunId = dfun_id,
268 iBinds = binds, iLoc = src_loc, iPrags = uprags }]
272 %************************************************************************
274 \subsection{Extracting generic instance declaration from class declarations}
276 %************************************************************************
278 @getGenericInstances@ extracts the generic instance declarations from a class
279 declaration. For exmaple
284 op{ x+y } (Inl v) = ...
285 op{ x+y } (Inr v) = ...
286 op{ x*y } (v :*: w) = ...
289 gives rise to the instance declarations
291 instance C (x+y) where
295 instance C (x*y) where
303 getGenericInstances :: Module -> [RenamedTyClDecl] -> TcM [InstInfo]
304 getGenericInstances mod class_decls
305 = mapTc (get_generics mod) class_decls `thenTc` \ gen_inst_infos ->
307 gen_inst_info = concat gen_inst_infos
309 ioToTc (dumpIfSet opt_D_dump_deriv "Generic instances"
310 (vcat (map pprInstInfo gen_inst_info))) `thenNF_Tc_`
311 returnTc gen_inst_info
313 get_generics mod decl@(ClassDecl context class_name tyvar_names
314 fundeps class_sigs def_methods pragmas
317 = returnTc [] -- The comon case:
318 -- no generic default methods, or
319 -- its an imported class decl (=> has no methods at all)
321 | otherwise -- A local class decl with generic default methods
322 = recoverNF_Tc (returnNF_Tc []) $
324 tcLookupClass class_name `thenTc` \ clas ->
326 -- Make an InstInfo out of each group
327 mapTc (mkGenericInstance mod clas loc) groups `thenTc` \ inst_infos ->
329 -- Check that there is only one InstInfo for each type constructor
330 -- The main way this can fail is if you write
331 -- f {| a+b |} ... = ...
332 -- f {| x+y |} ... = ...
333 -- Then at this point we'll have an InstInfo for each
335 bad_groups = [group | group <- equivClassesByUniq get_uniq inst_infos,
337 get_uniq inst = getUnique (simpleInstInfoTyCon inst)
339 mapTc (addErrTc . dupGenericInsts) bad_groups `thenTc_`
341 -- Check that there is an InstInfo for each generic type constructor
343 missing = genericTyCons `minusList` map simpleInstInfoTyCon inst_infos
345 checkTc (null missing) (missingGenericInstances missing) `thenTc_`
350 -- Group the declarations by type pattern
351 groups :: [(RenamedHsType, RenamedMonoBinds)]
352 groups = assocElts (getGenericBinds def_methods)
355 ---------------------------------
356 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
357 -- Takes a group of method bindings, finds the generic ones, and returns
358 -- them in finite map indexed by the type parameter in the definition.
360 getGenericBinds EmptyMonoBinds = emptyAssoc
361 getGenericBinds (AndMonoBinds m1 m2)
362 = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
364 getGenericBinds (FunMonoBind id infixop matches loc)
365 = mapAssoc wrap (foldr add emptyAssoc matches)
367 add match env = case maybeGenericMatch match of
369 Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
371 wrap ms = FunMonoBind id infixop ms loc
373 ---------------------------------
374 mkGenericInstance :: Module -> Class -> SrcLoc
375 -> (RenamedHsType, RenamedMonoBinds)
378 mkGenericInstance mod clas loc (hs_ty, binds)
379 -- Make a generic instance declaration
380 -- For example: instance (C a, C b) => C (a+b) where { binds }
382 = -- Extract the universally quantified type variables
383 tcTyVars (nameSetToList (extractHsTyVars hs_ty))
384 (kcHsSigType hs_ty) `thenTc` \ tyvars ->
385 tcExtendTyVarEnv tyvars $
387 -- Type-check the instance type, and check its form
388 tcHsSigType hs_ty `thenTc` \ inst_ty ->
389 checkTc (validGenericInstanceType inst_ty)
390 (badGenericInstanceType binds) `thenTc_`
392 -- Make the dictionary function.
393 newDFunName mod clas [inst_ty] loc `thenNF_Tc` \ dfun_name ->
395 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
397 dfun_id = mkDictFunId dfun_name clas tyvars inst_tys inst_theta
400 returnTc (InstInfo { iLocal = True,
401 iClass = clas, iTyVars = tyvars, iTys = inst_tys,
402 iTheta = inst_theta, iDFunId = dfun_id, iBinds = binds,
403 iLoc = loc, iPrags = [] })
407 %************************************************************************
409 \subsection{Type-checking instance declarations, pass 2}
411 %************************************************************************
414 tcInstDecls2 :: Bag InstInfo
415 -> NF_TcM (LIE, TcMonoBinds)
417 tcInstDecls2 inst_decls
418 = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
420 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
421 tc2 `thenNF_Tc` \ (lie2, binds2) ->
422 returnNF_Tc (lie1 `plusLIE` lie2,
423 binds1 `AndMonoBinds` binds2)
426 ======= New documentation starts here (Sept 92) ==============
428 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
429 the dictionary function for this instance declaration. For example
431 instance Foo a => Foo [a] where
435 might generate something like
437 dfun.Foo.List dFoo_a = let op1 x = ...
443 HOWEVER, if the instance decl has no context, then it returns a
444 bigger @HsBinds@ with declarations for each method. For example
446 instance Foo [a] where
452 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
453 const.Foo.op1.List a x = ...
454 const.Foo.op2.List a y = ...
456 This group may be mutually recursive, because (for example) there may
457 be no method supplied for op2 in which case we'll get
459 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
461 that is, the default method applied to the dictionary at this type.
463 What we actually produce in either case is:
465 AbsBinds [a] [dfun_theta_dicts]
466 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
467 { d = (sd1,sd2, ..., op1, op2, ...)
472 The "maybe" says that we only ask AbsBinds to make global constant methods
473 if the dfun_theta is empty.
476 For an instance declaration, say,
478 instance (C1 a, C2 b) => C (T a b) where
481 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
482 function whose type is
484 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
486 Notice that we pass it the superclass dictionaries at the instance type; this
487 is the ``Mark Jones optimisation''. The stuff before the "=>" here
488 is the @dfun_theta@ below.
490 First comes the easy case of a non-local instance decl.
493 tcInstDecl2 :: InstInfo -> NF_TcM (LIE, TcMonoBinds)
495 tcInstDecl2 (InstInfo { iClass = clas, iTyVars = inst_tyvars, iTys = inst_tys,
496 iTheta = inst_decl_theta, iDFunId = dfun_id,
497 iBinds = monobinds, iLoc = locn, iPrags = uprags })
498 | not (isLocallyDefined dfun_id)
499 = returnNF_Tc (emptyLIE, EmptyMonoBinds)
502 = -- Prime error recovery
503 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
506 -- Instantiate the instance decl with tc-style type variables
507 tcInstId dfun_id `thenNF_Tc` \ (inst_tyvars', dfun_theta', dict_ty') ->
509 (clas, inst_tys') = expectJust "tcInstDecl2" (splitDictTy_maybe dict_ty')
510 origin = InstanceDeclOrigin
512 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
514 dm_ids = [dm_id | (_, DefMeth dm_id) <- op_items]
515 sel_names = [idName sel_id | (sel_id, _) <- op_items]
517 -- Instantiate the theta found in the original instance decl
518 inst_decl_theta' = substTheta (mkTopTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars'))
521 -- Instantiate the super-class context with inst_tys
522 sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
524 -- Find any definitions in monobinds that aren't from the class
525 bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
527 -- Check that all the method bindings come from this class
528 mapTc (addErrTc . badMethodErr clas) bad_bndrs `thenNF_Tc_`
530 -- Create dictionary Ids from the specified instance contexts.
531 newClassDicts origin sc_theta' `thenNF_Tc` \ (sc_dicts, sc_dict_ids) ->
532 newDicts origin dfun_theta' `thenNF_Tc` \ (dfun_arg_dicts, dfun_arg_dicts_ids) ->
533 newDicts origin inst_decl_theta' `thenNF_Tc` \ (inst_decl_dicts, _) ->
534 newClassDicts origin [(clas,inst_tys')] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
536 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
537 tcExtendGlobalValEnv dm_ids (
538 -- Default-method Ids may be mentioned in synthesised RHSs
540 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
542 monobinds uprags True)
544 )) `thenTc` \ (method_binds_s, insts_needed_s, meth_lies_w_ids) ->
546 -- Deal with SPECIALISE instance pragmas by making them
547 -- look like SPECIALISE pragmas for the dfun
549 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
551 tcExtendGlobalValEnv [dfun_id] (
552 tcSpecSigs dfun_prags
553 ) `thenTc` \ (prag_binds, prag_lie) ->
555 -- Check the overloading constraints of the methods and superclasses
557 -- tcMethodBind has checked that the class_tyvars havn't
558 -- been unified with each other or another type, but we must
559 -- still zonk them before passing them to tcSimplifyAndCheck
560 zonkTcSigTyVars inst_tyvars' `thenNF_Tc` \ zonked_inst_tyvars ->
562 inst_tyvars_set = mkVarSet zonked_inst_tyvars
564 (meth_lies, meth_ids) = unzip meth_lies_w_ids
566 -- These insts are in scope; quite a few, eh?
567 avail_insts = this_dict `plusLIE`
568 dfun_arg_dicts `plusLIE`
570 unionManyBags meth_lies
572 methods_lie = plusLIEs insts_needed_s
575 -- Ditto method bindings
576 tcAddErrCtxt methodCtxt (
578 (ptext SLIT("instance declaration context"))
579 inst_tyvars_set -- Local tyvars
582 ) `thenTc` \ (const_lie1, lie_binds1) ->
584 -- Check that we *could* construct the superclass dictionaries,
585 -- even though we are *actually* going to pass the superclass dicts in;
586 -- the check ensures that the caller will never have
587 --a problem building them.
588 tcAddErrCtxt superClassCtxt (
590 (ptext SLIT("instance declaration context"))
591 inst_tyvars_set -- Local tyvars
592 inst_decl_dicts -- The instance dictionaries available
593 sc_dicts -- The superclass dicationaries reqd
595 -- Ignore the result; we're only doing
596 -- this to make sure it can be done.
598 -- Now do the simplification again, this time to get the
599 -- bindings; this time we use an enhanced "avails"
600 -- Ignore errors because they come from the *previous* tcSimplify
603 (ptext SLIT("instance declaration context"))
605 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
606 -- get bound by just selecting from this_dict!!
608 ) `thenTc` \ (const_lie2, lie_binds2) ->
611 -- Create the result bindings
613 dict_constr = classDataCon clas
614 scs_and_meths = sc_dict_ids ++ meth_ids
618 = -- Blatant special case for CCallable, CReturnable
619 -- If the dictionary is empty then we should never
620 -- select anything from it, so we make its RHS just
621 -- emit an error message. This in turn means that we don't
622 -- mention the constructor, which doesn't exist for CCallable, CReturnable
623 -- Hardly beautiful, but only three extra lines.
624 HsApp (TyApp (HsVar eRROR_ID) [(unUsgTy . idType) this_dict_id])
625 (HsLit (HsString msg))
627 | otherwise -- The common case
628 = mkHsConApp dict_constr inst_tys' (map HsVar (sc_dict_ids ++ meth_ids))
629 -- We don't produce a binding for the dict_constr; instead we
630 -- rely on the simplifier to unfold this saturated application
631 -- We do this rather than generate an HsCon directly, because
632 -- it means that the special cases (e.g. dictionary with only one
633 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
634 -- than needing to be repeated here.
637 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
639 dict_bind = VarMonoBind this_dict_id dict_rhs
640 method_binds = andMonoBindList method_binds_s
646 [(inst_tyvars', dfun_id, this_dict_id)]
647 emptyNameSet -- No inlines (yet)
648 (lie_binds1 `AndMonoBinds`
649 lie_binds2 `AndMonoBinds`
650 method_binds `AndMonoBinds`
653 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
654 main_bind `AndMonoBinds` prag_binds)
658 %************************************************************************
660 \subsection{Checking for a decent instance type}
662 %************************************************************************
664 @scrutiniseInstanceHead@ checks the type {\em and} its syntactic constraints:
665 it must normally look like: @instance Foo (Tycon a b c ...) ...@
667 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
668 flag is on, or (2)~the instance is imported (they must have been
669 compiled elsewhere). In these cases, we let them go through anyway.
671 We can also have instances for functions: @instance Foo (a -> b) ...@.
674 scrutiniseInstanceConstraint pred
675 | opt_AllowUndecidableInstances
678 | Just (clas,tys) <- getClassTys_maybe pred,
683 = addErrTc (instConstraintErr pred)
685 scrutiniseInstanceHead clas inst_taus
687 -- A user declaration of a CCallable/CReturnable instance
688 -- must be for a "boxed primitive" type.
689 (clas `hasKey` cCallableClassKey && not (ccallable_type first_inst_tau)) ||
690 (clas `hasKey` cReturnableClassKey && not (creturnable_type first_inst_tau))
691 = addErrTc (nonBoxedPrimCCallErr clas first_inst_tau)
694 -- It is obviously illegal to have an explicit instance
695 -- for something that we are also planning to `derive'
696 | maybeToBool alg_tycon_app_maybe && clas `elem` (tyConDerivings alg_tycon)
697 = addErrTc (derivingWhenInstanceExistsErr clas first_inst_tau)
698 -- Kind check will have ensured inst_taus is of length 1
700 -- Allow anything for AllowUndecidableInstances
701 | opt_AllowUndecidableInstances
704 -- If GlasgowExts then check at least one isn't a type variable
706 = if all isTyVarTy inst_taus then
707 addErrTc (instTypeErr clas inst_taus (text "There must be at least one non-type-variable in the instance head"))
711 -- WITH HASKELL 1.4, MUST HAVE C (T a b c)
712 | not (length inst_taus == 1 &&
713 maybeToBool maybe_tycon_app && -- Yes, there's a type constuctor
714 not (isSynTyCon tycon) && -- ...but not a synonym
715 all isTyVarTy arg_tys && -- Applied to type variables
716 length (varSetElems (tyVarsOfTypes arg_tys)) == length arg_tys
717 -- This last condition checks that all the type variables are distinct
719 = addErrTc (instTypeErr clas inst_taus
720 (text "the instance type must be of form (T a b c)" $$
721 text "where T is not a synonym, and a,b,c are distinct type variables")
728 (first_inst_tau : _) = inst_taus
730 -- Stuff for algebraic or -> type
731 maybe_tycon_app = splitTyConApp_maybe first_inst_tau
732 Just (tycon, arg_tys) = maybe_tycon_app
734 -- Stuff for an *algebraic* data type
735 alg_tycon_app_maybe = splitAlgTyConApp_maybe first_inst_tau
736 -- The "Alg" part looks through synonyms
737 Just (alg_tycon, _, _) = alg_tycon_app_maybe
739 ccallable_type ty = isFFIArgumentTy False {- Not safe call -} ty
740 creturnable_type ty = isFFIResultTy ty
744 %************************************************************************
746 \subsection{Error messages}
748 %************************************************************************
751 tcAddDeclCtxt decl thing_inside
758 (ClassDecl _ name _ _ _ _ _ _ loc) -> (name, loc, "class")
759 (TySynonym name _ _ loc) -> (name, loc, "type synonym")
760 (TyData NewType _ name _ _ _ _ _ loc _ _) -> (name, loc, "newtype")
761 (TyData DataType _ name _ _ _ _ _ loc _ _) -> (name, loc, "data type")
763 ctxt = hsep [ptext SLIT("In the"), text thing,
764 ptext SLIT("declaration for"), quotes (ppr name)]
768 instConstraintErr pred
769 = hang (ptext SLIT("Illegal constraint") <+>
770 quotes (pprPred pred) <+>
771 ptext SLIT("in instance context"))
772 4 (ptext SLIT("(Instance contexts must constrain only type variables)"))
774 badGenericInstanceType binds
775 = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
778 missingGenericInstances missing
779 = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
783 dupGenericInsts inst_infos
784 = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
785 nest 4 (vcat (map (ppr . simpleInstInfoTy) inst_infos)),
786 ptext SLIT("All the type patterns for a generic type constructor must be identical")
789 instTypeErr clas tys msg
790 = sep [ptext SLIT("Illegal instance declaration for") <+> quotes (pprConstraint clas tys),
794 derivingWhenInstanceExistsErr clas tycon
795 = hang (hsep [ptext SLIT("Deriving class"),
797 ptext SLIT("type"), quotes (ppr tycon)])
798 4 (ptext SLIT("when an explicit instance exists"))
800 nonBoxedPrimCCallErr clas inst_ty
801 = hang (ptext SLIT("Unacceptable instance type for ccall-ish class"))
802 4 (hsep [ ptext SLIT("class"), ppr clas, ptext SLIT("type"),
805 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
806 superClassCtxt = ptext SLIT("When checking the superclasses of an instance declaration")