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, tcLookupTy,
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 :: ValueEnv -- Contains IdInfo for dfun ids
168 -> Module -- Module for deriving
169 -> FixityEnv -- For derivings
170 -> RnNameSupply -- For renaming derivings
171 -> TcM s (Bag InstInfo,
174 tcInstDecls1 unf_env decls mod fixs rn_name_supply
175 = -- (1) Do the ordinary instance declarations
176 mapNF_Tc (tcInstDecl1 mod unf_env)
177 [inst_decl | InstD inst_decl <- decls] `thenNF_Tc` \ inst_info_bags ->
179 decl_inst_info = unionManyBags inst_info_bags
181 -- (2) Instances from "deriving" clauses; note that we only do derivings
182 -- for things in this module; we ignore deriving decls from
184 tcDeriving mod fixs rn_name_supply decl_inst_info `thenTc` \ (deriv_inst_info, deriv_binds) ->
186 -- (3) Instances from generic class declarations
187 mapTc (getGenericInstances mod)
188 [cl_decl | TyClD cl_decl <- decls, isClassDecl cl_decl] `thenTc` \ cls_inst_info ->
191 generic_insts = concat cls_inst_info
192 full_inst_info = deriv_inst_info `unionBags`
193 unionManyBags inst_info_bags `unionBags`
194 (listToBag generic_insts)
196 ioToTc (dumpIfSet opt_D_dump_deriv "Generic instances"
197 (vcat (map pprInstInfo generic_insts))) `thenNF_Tc_`
199 (returnTc (full_inst_info, deriv_binds))
203 tcInstDecl1 :: Module -> ValueEnv -> RenamedInstDecl -> NF_TcM s (Bag InstInfo)
204 -- Deal with a single instance declaration
205 tcInstDecl1 mod unf_env (InstDecl poly_ty binds uprags maybe_dfun_name src_loc)
206 = -- Prime error recovery, set source location
207 recoverNF_Tc (returnNF_Tc emptyBag) $
208 tcAddSrcLoc src_loc $
210 -- Type-check all the stuff before the "where"
211 tcHsSigType poly_ty `thenTc` \ poly_ty' ->
213 (tyvars, theta, dict_ty) = splitSigmaTy poly_ty'
214 (clas, inst_tys) = case splitDictTy_maybe dict_ty of
216 Nothing -> pprPanic "tcInstDecl1" (ppr poly_ty)
219 (case maybe_dfun_name of
220 Nothing -> -- A source-file instance declaration
222 -- Check for respectable instance type, and context
223 -- but only do this for non-imported instance decls.
224 -- Imported ones should have been checked already, and may indeed
225 -- contain something illegal in normal Haskell, notably
226 -- instance CCallable [Char]
227 scrutiniseInstanceHead clas inst_tys `thenNF_Tc_`
228 mapNF_Tc scrutiniseInstanceConstraint theta `thenNF_Tc_`
230 -- Make the dfun id and return it
231 newDFunName mod clas inst_tys src_loc `thenNF_Tc` \ dfun_name ->
232 returnNF_Tc (mkDictFunId dfun_name clas tyvars inst_tys theta)
234 Just dfun_name -> -- An interface-file instance declaration
235 -- Make the dfun id and add info from interface file
237 dfun_id = mkDictFunId dfun_name clas tyvars inst_tys theta
239 returnNF_Tc (tcAddImportedIdInfo unf_env dfun_id)
240 ) `thenNF_Tc` \ dfun_id ->
242 returnTc (unitBag (InstInfo clas tyvars inst_tys theta dfun_id binds src_loc uprags))
246 %************************************************************************
248 \subsection{Extracting generic instance declaration from class declarations}
250 %************************************************************************
252 @getGenericInstances@ extracts the generic instance declarations from a class
253 declaration. For exmaple
258 op{ x+y } (Inl v) = ...
259 op{ x+y } (Inr v) = ...
260 op{ x*y } (v :*: w) = ...
263 gives rise to the instance declarations
265 instance C (x+y) where
269 instance C (x*y) where
277 getGenericInstances :: Module -> RenamedTyClDecl -> TcM s [InstInfo]
278 getGenericInstances mod decl@(ClassDecl context class_name tyvar_names
279 fundeps class_sigs def_methods pragmas
282 = returnTc [] -- The comon case
285 = recoverNF_Tc (returnNF_Tc []) $
287 tcLookupTy class_name `thenTc` \ (AClass clas) ->
289 -- Make an InstInfo out of each group
290 mapTc (mkGenericInstance mod clas loc) groups `thenTc` \ inst_infos ->
292 -- Check that there is only one InstInfo for each type constructor
293 -- The main way this can fail is if you write
294 -- f {| a+b |} ... = ...
295 -- f {| x+y |} ... = ...
296 -- Then at this point we'll have an InstInfo for each
298 bad_groups = [group | group <- equivClassesByUniq get_uniq inst_infos,
300 get_uniq inst = getUnique (simpleInstInfoTyCon inst)
302 mapTc (addErrTc . dupGenericInsts) bad_groups `thenTc_`
304 -- Check that there is an InstInfo for each generic type constructor
306 missing = genericTyCons `minusList` map simpleInstInfoTyCon inst_infos
308 checkTc (null missing) (missingGenericInstances missing) `thenTc_`
313 -- Group the declarations by type pattern
314 groups :: [(RenamedHsType, RenamedMonoBinds)]
315 groups = assocElts (getGenericBinds def_methods)
318 ---------------------------------
319 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
320 -- Takes a group of method bindings, finds the generic ones, and returns
321 -- them in finite map indexed by the type parameter in the definition.
323 getGenericBinds EmptyMonoBinds = emptyAssoc
324 getGenericBinds (AndMonoBinds m1 m2)
325 = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
327 getGenericBinds (FunMonoBind id infixop matches loc)
328 = mapAssoc wrap (foldr add emptyAssoc matches)
330 add match env = case maybeGenericMatch match of
332 Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
334 wrap ms = FunMonoBind id infixop ms loc
336 ---------------------------------
337 mkGenericInstance :: Module -> Class -> SrcLoc
338 -> (RenamedHsType, RenamedMonoBinds)
341 mkGenericInstance mod clas loc (hs_ty, binds)
342 -- Make a generic instance declaration
343 -- For example: instance (C a, C b) => C (a+b) where { binds }
345 = -- Extract the universally quantified type variables
346 tcTyVars (nameSetToList (extractHsTyVars hs_ty))
347 (kcHsSigType hs_ty) `thenTc` \ tyvars ->
348 tcExtendTyVarEnv tyvars $
350 -- Type-check the instance type, and check its form
351 tcHsSigType hs_ty `thenTc` \ inst_ty ->
352 checkTc (validGenericInstanceType inst_ty)
353 (badGenericInstanceType binds) `thenTc_`
355 -- Make the dictionary function.
356 newDFunName mod clas [inst_ty] loc `thenNF_Tc` \ dfun_name ->
358 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
360 dfun_id = mkDictFunId dfun_name clas tyvars inst_tys inst_theta
363 returnTc (InstInfo clas tyvars inst_tys inst_theta dfun_id binds loc [])
364 -- The "[]" means "no pragmas"
368 %************************************************************************
370 \subsection{Type-checking instance declarations, pass 2}
372 %************************************************************************
375 tcInstDecls2 :: Bag InstInfo
376 -> NF_TcM s (LIE, TcMonoBinds)
378 tcInstDecls2 inst_decls
379 = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
381 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
382 tc2 `thenNF_Tc` \ (lie2, binds2) ->
383 returnNF_Tc (lie1 `plusLIE` lie2,
384 binds1 `AndMonoBinds` binds2)
387 ======= New documentation starts here (Sept 92) ==============
389 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
390 the dictionary function for this instance declaration. For example
392 instance Foo a => Foo [a] where
396 might generate something like
398 dfun.Foo.List dFoo_a = let op1 x = ...
404 HOWEVER, if the instance decl has no context, then it returns a
405 bigger @HsBinds@ with declarations for each method. For example
407 instance Foo [a] where
413 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
414 const.Foo.op1.List a x = ...
415 const.Foo.op2.List a y = ...
417 This group may be mutually recursive, because (for example) there may
418 be no method supplied for op2 in which case we'll get
420 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
422 that is, the default method applied to the dictionary at this type.
424 What we actually produce in either case is:
426 AbsBinds [a] [dfun_theta_dicts]
427 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
428 { d = (sd1,sd2, ..., op1, op2, ...)
433 The "maybe" says that we only ask AbsBinds to make global constant methods
434 if the dfun_theta is empty.
437 For an instance declaration, say,
439 instance (C1 a, C2 b) => C (T a b) where
442 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
443 function whose type is
445 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
447 Notice that we pass it the superclass dictionaries at the instance type; this
448 is the ``Mark Jones optimisation''. The stuff before the "=>" here
449 is the @dfun_theta@ below.
451 First comes the easy case of a non-local instance decl.
454 tcInstDecl2 :: InstInfo -> NF_TcM s (LIE, TcMonoBinds)
456 tcInstDecl2 (InstInfo clas inst_tyvars inst_tys
460 | not (isLocallyDefined dfun_id)
461 = returnNF_Tc (emptyLIE, EmptyMonoBinds)
464 = -- Prime error recovery
465 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
468 -- Instantiate the instance decl with tc-style type variables
469 tcInstId dfun_id `thenNF_Tc` \ (inst_tyvars', dfun_theta', dict_ty') ->
471 (clas, inst_tys') = expectJust "tcInstDecl2" (splitDictTy_maybe dict_ty')
472 origin = InstanceDeclOrigin
474 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
476 dm_ids = [dm_id | (_, DefMeth dm_id) <- op_items]
477 sel_names = [idName sel_id | (sel_id, _) <- op_items]
479 -- Instantiate the theta found in the original instance decl
480 inst_decl_theta' = substTheta (mkTopTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars'))
483 -- Instantiate the super-class context with inst_tys
484 sc_theta' = substClasses (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
486 -- Find any definitions in monobinds that aren't from the class
487 bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
489 -- Check that all the method bindings come from this class
490 mapTc (addErrTc . badMethodErr clas) bad_bndrs `thenNF_Tc_`
492 -- Create dictionary Ids from the specified instance contexts.
493 newClassDicts origin sc_theta' `thenNF_Tc` \ (sc_dicts, sc_dict_ids) ->
494 newDicts origin dfun_theta' `thenNF_Tc` \ (dfun_arg_dicts, dfun_arg_dicts_ids) ->
495 newDicts origin inst_decl_theta' `thenNF_Tc` \ (inst_decl_dicts, _) ->
496 newClassDicts origin [(clas,inst_tys')] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
498 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
499 tcExtendGlobalValEnv dm_ids (
500 -- Default-method Ids may be mentioned in synthesised RHSs
502 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
504 monobinds uprags True)
506 )) `thenTc` \ (method_binds_s, insts_needed_s, meth_lies_w_ids) ->
508 -- Deal with SPECIALISE instance pragmas by making them
509 -- look like SPECIALISE pragmas for the dfun
511 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
513 tcExtendGlobalValEnv [dfun_id] (
514 tcSpecSigs dfun_prags
515 ) `thenTc` \ (prag_binds, prag_lie) ->
517 -- Check the overloading constraints of the methods and superclasses
519 -- tcMethodBind has checked that the class_tyvars havn't
520 -- been unified with each other or another type, but we must
521 -- still zonk them before passing them to tcSimplifyAndCheck
522 zonkTcSigTyVars inst_tyvars' `thenNF_Tc` \ zonked_inst_tyvars ->
524 inst_tyvars_set = mkVarSet zonked_inst_tyvars
526 (meth_lies, meth_ids) = unzip meth_lies_w_ids
528 -- These insts are in scope; quite a few, eh?
529 avail_insts = this_dict `plusLIE`
530 dfun_arg_dicts `plusLIE`
532 unionManyBags meth_lies
534 methods_lie = plusLIEs insts_needed_s
537 -- Ditto method bindings
538 tcAddErrCtxt methodCtxt (
540 (ptext SLIT("instance declaration context"))
541 inst_tyvars_set -- Local tyvars
544 ) `thenTc` \ (const_lie1, lie_binds1) ->
546 -- Check that we *could* construct the superclass dictionaries,
547 -- even though we are *actually* going to pass the superclass dicts in;
548 -- the check ensures that the caller will never have
549 --a problem building them.
550 tcAddErrCtxt superClassCtxt (
552 (ptext SLIT("instance declaration context"))
553 inst_tyvars_set -- Local tyvars
554 inst_decl_dicts -- The instance dictionaries available
555 sc_dicts -- The superclass dicationaries reqd
557 -- Ignore the result; we're only doing
558 -- this to make sure it can be done.
560 -- Now do the simplification again, this time to get the
561 -- bindings; this time we use an enhanced "avails"
562 -- Ignore errors because they come from the *previous* tcSimplify
565 (ptext SLIT("instance declaration context"))
567 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
568 -- get bound by just selecting from this_dict!!
570 ) `thenTc` \ (const_lie2, lie_binds2) ->
573 -- Create the result bindings
575 dict_constr = classDataCon clas
576 scs_and_meths = sc_dict_ids ++ meth_ids
580 = -- Blatant special case for CCallable, CReturnable
581 -- If the dictionary is empty then we should never
582 -- select anything from it, so we make its RHS just
583 -- emit an error message. This in turn means that we don't
584 -- mention the constructor, which doesn't exist for CCallable, CReturnable
585 -- Hardly beautiful, but only three extra lines.
586 HsApp (TyApp (HsVar eRROR_ID) [(unUsgTy . idType) this_dict_id])
587 (HsLit (HsString msg))
589 | otherwise -- The common case
590 = mkHsConApp dict_constr inst_tys' (map HsVar (sc_dict_ids ++ meth_ids))
591 -- We don't produce a binding for the dict_constr; instead we
592 -- rely on the simplifier to unfold this saturated application
593 -- We do this rather than generate an HsCon directly, because
594 -- it means that the special cases (e.g. dictionary with only one
595 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
596 -- than needing to be repeated here.
599 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
601 dict_bind = VarMonoBind this_dict_id dict_rhs
602 method_binds = andMonoBindList method_binds_s
608 [(inst_tyvars', dfun_id, this_dict_id)]
609 emptyNameSet -- No inlines (yet)
610 (lie_binds1 `AndMonoBinds`
611 lie_binds2 `AndMonoBinds`
612 method_binds `AndMonoBinds`
615 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
616 main_bind `AndMonoBinds` prag_binds)
620 %************************************************************************
622 \subsection{Checking for a decent instance type}
624 %************************************************************************
626 @scrutiniseInstanceHead@ checks the type {\em and} its syntactic constraints:
627 it must normally look like: @instance Foo (Tycon a b c ...) ...@
629 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
630 flag is on, or (2)~the instance is imported (they must have been
631 compiled elsewhere). In these cases, we let them go through anyway.
633 We can also have instances for functions: @instance Foo (a -> b) ...@.
636 scrutiniseInstanceConstraint pred
637 | opt_AllowUndecidableInstances
640 | Just (clas,tys) <- getClassTys_maybe pred,
645 = addErrTc (instConstraintErr pred)
647 scrutiniseInstanceHead clas inst_taus
649 -- A user declaration of a CCallable/CReturnable instance
650 -- must be for a "boxed primitive" type.
651 (clas `hasKey` cCallableClassKey && not (ccallable_type first_inst_tau)) ||
652 (clas `hasKey` cReturnableClassKey && not (creturnable_type first_inst_tau))
653 = addErrTc (nonBoxedPrimCCallErr clas first_inst_tau)
656 -- It is obviously illegal to have an explicit instance
657 -- for something that we are also planning to `derive'
658 | maybeToBool alg_tycon_app_maybe && clas `elem` (tyConDerivings alg_tycon)
659 = addErrTc (derivingWhenInstanceExistsErr clas first_inst_tau)
660 -- Kind check will have ensured inst_taus is of length 1
662 -- Allow anything for AllowUndecidableInstances
663 | opt_AllowUndecidableInstances
666 -- If GlasgowExts then check at least one isn't a type variable
668 = if all isTyVarTy inst_taus then
669 addErrTc (instTypeErr clas inst_taus (text "There must be at least one non-type-variable in the instance head"))
673 -- WITH HASKELL 1.4, MUST HAVE C (T a b c)
674 | not (length inst_taus == 1 &&
675 maybeToBool maybe_tycon_app && -- Yes, there's a type constuctor
676 not (isSynTyCon tycon) && -- ...but not a synonym
677 all isTyVarTy arg_tys && -- Applied to type variables
678 length (varSetElems (tyVarsOfTypes arg_tys)) == length arg_tys
679 -- This last condition checks that all the type variables are distinct
681 = addErrTc (instTypeErr clas inst_taus
682 (text "the instance type must be of form (T a b c)" $$
683 text "where T is not a synonym, and a,b,c are distinct type variables")
690 (first_inst_tau : _) = inst_taus
692 -- Stuff for algebraic or -> type
693 maybe_tycon_app = splitTyConApp_maybe first_inst_tau
694 Just (tycon, arg_tys) = maybe_tycon_app
696 -- Stuff for an *algebraic* data type
697 alg_tycon_app_maybe = splitAlgTyConApp_maybe first_inst_tau
698 -- The "Alg" part looks through synonyms
699 Just (alg_tycon, _, _) = alg_tycon_app_maybe
701 ccallable_type ty = isFFIArgumentTy False {- Not safe call -} ty
702 creturnable_type ty = isFFIResultTy ty
706 %************************************************************************
708 \subsection{Error messages}
710 %************************************************************************
713 tcAddDeclCtxt decl thing_inside
720 (ClassDecl _ name _ _ _ _ _ _ loc) -> (name, loc, "class")
721 (TySynonym name _ _ loc) -> (name, loc, "type synonym")
722 (TyData NewType _ name _ _ _ _ _ loc _ _) -> (name, loc, "newtype")
723 (TyData DataType _ name _ _ _ _ _ loc _ _) -> (name, loc, "data type")
725 ctxt = hsep [ptext SLIT("In the"), text thing,
726 ptext SLIT("declaration for"), quotes (ppr name)]
730 instConstraintErr pred
731 = hang (ptext SLIT("Illegal constraint") <+>
732 quotes (pprPred pred) <+>
733 ptext SLIT("in instance context"))
734 4 (ptext SLIT("(Instance contexts must constrain only type variables)"))
736 badGenericInstanceType binds
737 = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
740 missingGenericInstances missing
741 = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
745 dupGenericInsts inst_infos
746 = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
747 nest 4 (vcat (map (ppr . simpleInstInfoTy) inst_infos)),
748 ptext SLIT("All the type patterns for a generic type constructor must be identical")
751 instTypeErr clas tys msg
752 = sep [ptext SLIT("Illegal instance declaration for") <+> quotes (pprConstraint clas tys),
756 derivingWhenInstanceExistsErr clas tycon
757 = hang (hsep [ptext SLIT("Deriving class"),
759 ptext SLIT("type"), quotes (ppr tycon)])
760 4 (ptext SLIT("when an explicit instance exists"))
762 nonBoxedPrimCCallErr clas inst_ty
763 = hang (ptext SLIT("Unacceptable instance type for ccall-ish class"))
764 4 (hsep [ ptext SLIT("class"), ppr clas, ptext SLIT("type"),
767 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
768 superClassCtxt = ptext SLIT("When checking the superclasses of an instance declaration")