[project @ 1999-11-29 17:34:14 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcInstDcls.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcInstDecls]{Typechecking instance declarations}
5
6 \begin{code}
7 module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn            ( HsDecl(..), InstDecl(..),
12                           HsBinds(..), MonoBinds(..),
13                           HsExpr(..), InPat(..), HsLit(..), Sig(..),
14                           andMonoBindList
15                         )
16 import RnHsSyn          ( RenamedHsBinds, RenamedInstDecl, RenamedHsDecl )
17 import TcHsSyn          ( TcMonoBinds,
18                           maybeBoxedPrimType
19                         )
20
21 import TcBinds          ( tcSpecSigs )
22 import TcClassDcl       ( tcMethodBind, checkFromThisClass )
23 import TcMonad
24 import RnMonad          ( RnNameSupply, Fixities )
25 import Inst             ( Inst, InstOrigin(..),
26                           newDicts, LIE, emptyLIE, plusLIE, plusLIEs )
27 import TcDeriv          ( tcDeriving )
28 import TcEnv            ( ValueEnv, tcExtendGlobalValEnv, tcExtendTyVarEnvForMeths,
29                           tcAddImportedIdInfo, tcInstId
30                         )
31 import TcInstUtil       ( InstInfo(..), classDataCon )
32 import TcMonoType       ( tcHsTopType )
33 import TcSimplify       ( tcSimplifyAndCheck )
34 import TcType           ( TcTyVar, zonkTcTyVarBndr )
35
36 import Bag              ( emptyBag, unitBag, unionBags, unionManyBags,
37                           foldBag, Bag
38                         )
39 import CmdLineOpts      ( opt_GlasgowExts, opt_AllowUndecidableInstances )
40 import Class            ( classBigSig, Class )
41 import Var              ( idName, idType, Id, TyVar )
42 import DataCon          ( isNullaryDataCon, splitProductType_maybe, dataConId )
43 import Maybes           ( maybeToBool, catMaybes, expectJust )
44 import MkId             ( mkDictFunId )
45 import Module           ( ModuleName )
46 import Name             ( isLocallyDefined, NamedThing(..)      )
47 import NameSet          ( emptyNameSet )
48 import PrelInfo         ( eRROR_ID )
49 import PprType          ( pprConstraint )
50 import SrcLoc           ( SrcLoc )
51 import TyCon            ( isSynTyCon, isDataTyCon, tyConDerivings )
52 import Type             ( Type, isUnLiftedType, mkTyVarTys,
53                           splitSigmaTy, isTyVarTy,
54                           splitTyConApp_maybe, splitDictTy_maybe, unUsgTy,
55                           splitAlgTyConApp_maybe,
56                           tyVarsOfTypes
57                         )
58 import Subst            ( mkTopTyVarSubst, substTheta )
59 import VarSet           ( mkVarSet, varSetElems )
60 import TysPrim          ( byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
61 import TysWiredIn       ( stringTy )
62 import Unique           ( Unique, cCallableClassKey, cReturnableClassKey, Uniquable(..) )
63 import Outputable
64 \end{code}
65
66 Typechecking instance declarations is done in two passes. The first
67 pass, made by @tcInstDecls1@, collects information to be used in the
68 second pass.
69
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.
75
76
77 Here is the overall algorithm.
78 Assume that we have an instance declaration
79
80     instance c => k (t tvs) where b
81
82 \begin{enumerate}
83 \item
84 $LIE_c$ is the LIE for the context of class $c$
85 \item
86 $betas_bar$ is the free variables in the class method type, excluding the
87    class variable
88 \item
89 $LIE_cop$ is the LIE constraining a particular class method
90 \item
91 $tau_cop$ is the tau type of a class method
92 \item
93 $LIE_i$ is the LIE for the context of instance $i$
94 \item
95 $X$ is the instance constructor tycon
96 \item
97 $gammas_bar$ is the set of type variables of the instance
98 \item
99 $LIE_iop$ is the LIE for a particular class method instance
100 \item
101 $tau_iop$ is the tau type for this instance of a class method
102 \item
103 $alpha$ is the class variable
104 \item
105 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
106 \item
107 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
108 \end{enumerate}
109
110 ToDo: Update the list above with names actually in the code.
111
112 \begin{enumerate}
113 \item
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.
117 \item
118 Then process each method in turn.
119 \item
120 order the instance methods according to the ordering of the class methods
121 \item
122 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
123 \item
124 Create final dictionary function from bindings generated already
125 \begin{pseudocode}
126 df = lambda inst_tyvars
127        lambda LIEI
128          let Bop1
129              Bop2
130              ...
131              Bopn
132          and dbinds_super
133               in <op1,op2,...,opn,sd1,...,sdm>
134 \end{pseudocode}
135 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
136 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
137 \end{enumerate}
138
139 \begin{code}
140 tcInstDecls1 :: ValueEnv                -- Contains IdInfo for dfun ids
141              -> [RenamedHsDecl]
142              -> ModuleName                      -- module name for deriving
143              -> Fixities
144              -> RnNameSupply                    -- for renaming derivings
145              -> TcM s (Bag InstInfo,
146                        RenamedHsBinds)
147
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 ->
152     let
153         decl_inst_info = unionManyBags inst_info_bags
154     in
155         -- Handle "derived" instances; note that we only do derivings
156         -- for things in this module; we ignore deriving decls from
157         -- interfaces!
158     tcDeriving mod_name fixs rn_name_supply decl_inst_info
159                         `thenTc` \ (deriv_inst_info, deriv_binds) ->
160
161     let
162         full_inst_info = deriv_inst_info `unionBags` decl_inst_info
163     in
164     returnTc (full_inst_info, deriv_binds)
165
166
167 tcInstDecl1 :: ValueEnv -> RenamedInstDecl -> NF_TcM s (Bag InstInfo)
168
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                 $
173
174         -- Type-check all the stuff before the "where"
175     tcHsTopType poly_ty                 `thenTc` \ poly_ty' ->
176     let
177         (tyvars, theta, dict_ty) = splitSigmaTy poly_ty'
178         (clas, inst_tys)         = case splitDictTy_maybe dict_ty of
179                                      Nothing   -> pprPanic "tcInstDecl1" (ppr poly_ty)
180                                      Just pair -> pair
181     in
182
183         -- Check for respectable instance type, and context
184         -- but only do this for non-imported instance decls.
185         -- Imported ones should have been checked already, and may indeed
186         -- contain something illegal in normal Haskell, notably
187         --      instance CCallable [Char] 
188     (if isLocallyDefined dfun_name then
189         scrutiniseInstanceHead clas inst_tys    `thenNF_Tc_`
190         mapNF_Tc scrutiniseInstanceConstraint theta
191      else
192         returnNF_Tc []
193      )                                          `thenNF_Tc_`
194
195         -- Make the dfun id
196     let
197         dfun_id = mkDictFunId dfun_name clas tyvars inst_tys theta
198
199         -- Add info from interface file
200         final_dfun_id = tcAddImportedIdInfo unf_env dfun_id
201     in
202     returnTc (unitBag (InstInfo clas tyvars inst_tys theta      
203                                 final_dfun_id
204                                 binds src_loc uprags))
205 \end{code}
206
207
208 %************************************************************************
209 %*                                                                      *
210 \subsection{Type-checking instance declarations, pass 2}
211 %*                                                                      *
212 %************************************************************************
213
214 \begin{code}
215 tcInstDecls2 :: Bag InstInfo
216              -> NF_TcM s (LIE, TcMonoBinds)
217
218 tcInstDecls2 inst_decls
219   = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
220   where
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)
225 \end{code}
226
227
228 ======= New documentation starts here (Sept 92)  ==============
229
230 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
231 the dictionary function for this instance declaration.  For example
232 \begin{verbatim}
233         instance Foo a => Foo [a] where
234                 op1 x = ...
235                 op2 y = ...
236 \end{verbatim}
237 might generate something like
238 \begin{verbatim}
239         dfun.Foo.List dFoo_a = let op1 x = ...
240                                    op2 y = ...
241                                in
242                                    Dict [op1, op2]
243 \end{verbatim}
244
245 HOWEVER, if the instance decl has no context, then it returns a
246 bigger @HsBinds@ with declarations for each method.  For example
247 \begin{verbatim}
248         instance Foo [a] where
249                 op1 x = ...
250                 op2 y = ...
251 \end{verbatim}
252 might produce
253 \begin{verbatim}
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 = ...
257 \end{verbatim}
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
260 \begin{verbatim}
261         const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
262 \end{verbatim}
263 that is, the default method applied to the dictionary at this type.
264
265 What we actually produce in either case is:
266
267         AbsBinds [a] [dfun_theta_dicts]
268                  [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
269                  { d = (sd1,sd2, ..., op1, op2, ...)
270                    op1 = ...
271                    op2 = ...
272                  }
273
274 The "maybe" says that we only ask AbsBinds to make global constant methods
275 if the dfun_theta is empty.
276
277                 
278 For an instance declaration, say,
279
280         instance (C1 a, C2 b) => C (T a b) where
281                 ...
282
283 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
284 function whose type is
285
286         (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
287
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.
291
292 First comes the easy case of a non-local instance decl.
293
294 \begin{code}
295 tcInstDecl2 :: InstInfo -> NF_TcM s (LIE, TcMonoBinds)
296
297 tcInstDecl2 (InstInfo clas inst_tyvars inst_tys
298                       inst_decl_theta
299                       dfun_id monobinds
300                       locn uprags)
301   | not (isLocallyDefined dfun_id)
302   = returnNF_Tc (emptyLIE, EmptyMonoBinds)
303
304 {-
305   -- I deleted this "optimisation" because when importing these
306   -- instance decls the renamer would look for the dfun bindings and they weren't there.
307   -- This would be fixable, but it seems simpler just to produce a tiny void binding instead,
308   -- even though it's never used.
309
310         -- This case deals with CCallable etc, which don't need any bindings
311   | isNoDictClass clas                  
312   = returnNF_Tc (emptyLIE, EmptyBinds)
313 -}
314
315   | otherwise
316   =      -- Prime error recovery
317     recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds))  $
318     tcAddSrcLoc locn                                       $
319
320         -- Instantiate the instance decl with tc-style type variables
321     tcInstId dfun_id            `thenNF_Tc` \ (inst_tyvars', dfun_theta', dict_ty') ->
322     let
323         (clas, inst_tys')       = expectJust "tcInstDecl2" (splitDictTy_maybe dict_ty')
324
325         origin                  = InstanceDeclOrigin
326
327         (class_tyvars, sc_theta, sc_sel_ids, op_items) = classBigSig clas
328
329         dm_ids = [dm_id | (_, dm_id, _) <- op_items]
330
331         -- Instantiate the theta found in the original instance decl
332         inst_decl_theta' = substTheta (mkTopTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars'))
333                                       inst_decl_theta
334
335          -- Instantiate the super-class context with inst_tys
336         sc_theta' = substTheta (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
337     in
338          -- Create dictionary Ids from the specified instance contexts.
339     newDicts origin sc_theta'           `thenNF_Tc` \ (sc_dicts,        sc_dict_ids) ->
340     newDicts origin dfun_theta'         `thenNF_Tc` \ (dfun_arg_dicts,  dfun_arg_dicts_ids)  ->
341     newDicts origin inst_decl_theta'    `thenNF_Tc` \ (inst_decl_dicts, _) ->
342     newDicts origin [(clas,inst_tys')]  `thenNF_Tc` \ (this_dict,       [this_dict_id]) ->
343
344          -- Check that all the method bindings come from this class
345     checkFromThisClass clas op_items monobinds          `thenNF_Tc_`
346
347     tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
348         tcExtendGlobalValEnv dm_ids (
349                 -- Default-method Ids may be mentioned in synthesised RHSs 
350
351         mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys' inst_decl_theta'
352                                      monobinds uprags True) 
353                        op_items
354     ))                  `thenTc` \ (method_binds_s, insts_needed_s, meth_lies_w_ids) ->
355
356         -- Deal with SPECIALISE instance pragmas by making them
357         -- look like SPECIALISE pragmas for the dfun
358     let
359         dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
360     in
361     tcExtendGlobalValEnv [dfun_id] (
362         tcSpecSigs dfun_prags
363     )                                   `thenTc` \ (prag_binds, prag_lie) ->
364
365         -- Check the overloading constraints of the methods and superclasses
366
367         -- tcMethodBind has checked that the class_tyvars havn't
368         -- been unified with each other or another type, but we must
369         -- still zonk them
370     mapNF_Tc zonkTcTyVarBndr inst_tyvars'       `thenNF_Tc` \ zonked_inst_tyvars ->
371     let
372         inst_tyvars_set = mkVarSet zonked_inst_tyvars
373
374         (meth_lies, meth_ids) = unzip meth_lies_w_ids
375
376                  -- These insts are in scope; quite a few, eh?
377         avail_insts = this_dict                 `plusLIE` 
378                       dfun_arg_dicts            `plusLIE`
379                       sc_dicts                  `plusLIE`
380                       unionManyBags meth_lies
381
382         methods_lie = plusLIEs insts_needed_s
383     in
384
385         -- Ditto method bindings
386     tcAddErrCtxt methodCtxt (
387       tcSimplifyAndCheck
388                  (ptext SLIT("instance declaration context"))
389                  inst_tyvars_set                        -- Local tyvars
390                  avail_insts
391                  methods_lie
392     )                                            `thenTc` \ (const_lie1, lie_binds1) ->
393     
394         -- Check that we *could* construct the superclass dictionaries,
395         -- even though we are *actually* going to pass the superclass dicts in;
396         -- the check ensures that the caller will never have 
397         --a problem building them.
398     tcAddErrCtxt superClassCtxt (
399       tcSimplifyAndCheck
400                  (ptext SLIT("instance declaration context"))
401                  inst_tyvars_set                -- Local tyvars
402                  inst_decl_dicts                -- The instance dictionaries available
403                  sc_dicts                       -- The superclass dicationaries reqd
404     )                                   `thenTc` \ _ -> 
405                                                 -- Ignore the result; we're only doing
406                                                 -- this to make sure it can be done.
407
408         -- Now do the simplification again, this time to get the
409         -- bindings; this time we use an enhanced "avails"
410         -- Ignore errors because they come from the *previous* tcSimplify
411     discardErrsTc (
412         tcSimplifyAndCheck
413                  (ptext SLIT("instance declaration context"))
414                  inst_tyvars_set
415                  dfun_arg_dicts         -- NB! Don't include this_dict here, else the sc_dicts
416                                         -- get bound by just selecting from this_dict!!
417                  sc_dicts
418     )                                            `thenTc` \ (const_lie2, lie_binds2) ->
419         
420
421         -- Create the result bindings
422     let
423         dict_constr   = classDataCon clas
424         scs_and_meths = sc_dict_ids ++ meth_ids
425
426         dict_rhs
427           | null scs_and_meths
428           =     -- Blatant special case for CCallable, CReturnable
429                 -- If the dictionary is empty then we should never
430                 -- select anything from it, so we make its RHS just
431                 -- emit an error message.  This in turn means that we don't
432                 -- mention the constructor, which doesn't exist for CCallable, CReturnable
433                 -- Hardly beautiful, but only three extra lines.
434             HsApp (TyApp (HsVar eRROR_ID) [(unUsgTy . idType) this_dict_id])
435                   (HsLitOut (HsString msg) stringTy)
436
437           | otherwise   -- The common case
438           = foldl HsApp (TyApp (HsVar (dataConId dict_constr)) inst_tys')
439                                (map HsVar (sc_dict_ids ++ meth_ids))
440                 -- We don't produce a binding for the dict_constr; instead we
441                 -- rely on the simplifier to unfold this saturated application
442                 -- We do this rather than generate an HsCon directly, because
443                 -- it means that the special cases (e.g. dictionary with only one
444                 -- member) are dealt with by the common MkId.mkDataConId code rather
445                 -- than needing to be repeated here.
446
447           where
448             msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
449
450         dict_bind    = VarMonoBind this_dict_id dict_rhs
451         method_binds = andMonoBindList method_binds_s
452
453         main_bind
454           = AbsBinds
455                  zonked_inst_tyvars
456                  dfun_arg_dicts_ids
457                  [(inst_tyvars', dfun_id, this_dict_id)] 
458                  emptyNameSet           -- No inlines (yet)
459                  (lie_binds1    `AndMonoBinds` 
460                   lie_binds2    `AndMonoBinds`
461                   method_binds  `AndMonoBinds`
462                   dict_bind)
463     in
464     returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
465               main_bind `AndMonoBinds` prag_binds)
466 \end{code}
467
468
469 %************************************************************************
470 %*                                                                      *
471 \subsection{Checking for a decent instance type}
472 %*                                                                      *
473 %************************************************************************
474
475 @scrutiniseInstanceHead@ checks the type {\em and} its syntactic constraints:
476 it must normally look like: @instance Foo (Tycon a b c ...) ...@
477
478 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
479 flag is on, or (2)~the instance is imported (they must have been
480 compiled elsewhere). In these cases, we let them go through anyway.
481
482 We can also have instances for functions: @instance Foo (a -> b) ...@.
483
484 \begin{code}
485 scrutiniseInstanceConstraint (clas, tys)
486   |  all isTyVarTy tys 
487   || opt_AllowUndecidableInstances = returnNF_Tc ()
488   | otherwise                      = addErrTc (instConstraintErr clas tys)
489
490 scrutiniseInstanceHead clas inst_taus
491   |     -- CCALL CHECK (a).... urgh!
492         -- To verify that a user declaration of a CCallable/CReturnable 
493         -- instance is OK, we must be able to see the constructor(s)
494         -- of the instance type (see next guard.)
495         --  
496         -- We flag this separately to give a more precise error msg.
497         --
498      (getUnique clas == cCallableClassKey || getUnique clas == cReturnableClassKey)
499   && is_alg_tycon_app && not constructors_visible
500   = addErrTc (invisibleDataConPrimCCallErr clas first_inst_tau)
501
502   |     -- CCALL CHECK (b) 
503         -- A user declaration of a CCallable/CReturnable instance
504         -- must be for a "boxed primitive" type.
505     (getUnique clas == cCallableClassKey   && not (ccallable_type   first_inst_tau)) ||
506     (getUnique clas == cReturnableClassKey && not (creturnable_type first_inst_tau))
507   = addErrTc (nonBoxedPrimCCallErr clas first_inst_tau)
508
509         -- DERIVING CHECK
510         -- It is obviously illegal to have an explicit instance
511         -- for something that we are also planning to `derive'
512   | maybeToBool alg_tycon_app_maybe && clas `elem` (tyConDerivings alg_tycon)
513   = addErrTc (derivingWhenInstanceExistsErr clas first_inst_tau)
514            -- Kind check will have ensured inst_taus is of length 1
515
516         -- Allow anything for AllowUndecidableInstances
517   | opt_AllowUndecidableInstances
518   = returnNF_Tc ()
519
520         -- If GlasgowExts then check at least one isn't a type variable
521   | opt_GlasgowExts 
522   = if all isTyVarTy inst_taus then
523         addErrTc (instTypeErr clas inst_taus (text "There must be at least one non-type-variable in the instance head"))
524     else
525         returnNF_Tc ()
526
527         -- WITH HASKELL 1.4, MUST HAVE C (T a b c)
528   |  not (length inst_taus == 1 &&
529           maybeToBool maybe_tycon_app &&        -- Yes, there's a type constuctor
530           not (isSynTyCon tycon) &&             -- ...but not a synonym
531           all isTyVarTy arg_tys &&              -- Applied to type variables
532           length (varSetElems (tyVarsOfTypes arg_tys)) == length arg_tys
533                  -- This last condition checks that all the type variables are distinct
534      )
535   = addErrTc (instTypeErr clas inst_taus
536                         (text "the instance type must be of form (T a b c)" $$
537                          text "where T is not a synonym, and a,b,c are distinct type variables")
538     )
539
540   | otherwise
541   = returnNF_Tc ()
542
543   where
544     (first_inst_tau : _)       = inst_taus
545
546         -- Stuff for algebraic or -> type
547     maybe_tycon_app       = splitTyConApp_maybe first_inst_tau
548     Just (tycon, arg_tys) = maybe_tycon_app
549
550         -- Stuff for an *algebraic* data type
551     alg_tycon_app_maybe            = splitAlgTyConApp_maybe first_inst_tau
552                                         -- The "Alg" part looks through synonyms
553     is_alg_tycon_app               = maybeToBool alg_tycon_app_maybe
554     Just (alg_tycon, _, data_cons) = alg_tycon_app_maybe
555
556     constructors_visible = not (null data_cons)
557  
558
559 -- These conditions come directly from what the DsCCall is capable of.
560 -- Totally grotesque.  Green card should solve this.
561
562 ccallable_type   ty = isUnLiftedType ty ||                              -- Allow CCallable Int# etc
563                       maybeToBool (maybeBoxedPrimType ty) ||    -- Ditto Int etc
564                       ty == stringTy ||
565                       byte_arr_thing
566   where
567     byte_arr_thing = case splitProductType_maybe ty of
568                         Just (tycon, ty_args, data_con, [data_con_arg_ty1, data_con_arg_ty2, data_con_arg_ty3]) ->
569                                 maybeToBool maybe_arg3_tycon &&
570                                 (arg3_tycon == byteArrayPrimTyCon ||
571                                  arg3_tycon == mutableByteArrayPrimTyCon)
572                              where
573                                 maybe_arg3_tycon    = splitTyConApp_maybe data_con_arg_ty3
574                                 Just (arg3_tycon,_) = maybe_arg3_tycon
575
576                         other -> False
577
578 creturnable_type ty = maybeToBool (maybeBoxedPrimType ty) ||
579                         -- Or, a data type with a single nullary constructor
580                       case (splitAlgTyConApp_maybe ty) of
581                         Just (tycon, tys_applied, [data_con])
582                                 -> isNullaryDataCon data_con
583                         other -> False
584 \end{code}
585
586 \begin{code}
587 instConstraintErr clas tys
588   = hang (ptext SLIT("Illegal constaint") <+> 
589           quotes (pprConstraint clas tys) <+> 
590           ptext SLIT("in instance context"))
591          4 (ptext SLIT("(Instance contexts must constrain only type variables)"))
592         
593 instTypeErr clas tys msg
594   = sep [ptext SLIT("Illegal instance declaration for") <+> quotes (pprConstraint clas tys),
595          nest 4 (parens msg)
596     ]
597
598 derivingWhenInstanceExistsErr clas tycon
599   = hang (hsep [ptext SLIT("Deriving class"), 
600                        quotes (ppr clas), 
601                        ptext SLIT("type"), quotes (ppr tycon)])
602          4 (ptext SLIT("when an explicit instance exists"))
603
604 nonBoxedPrimCCallErr clas inst_ty
605   = hang (ptext SLIT("Unacceptable instance type for ccall-ish class"))
606          4 (hsep [ ptext SLIT("class"), ppr clas, ptext SLIT("type"),
607                         ppr inst_ty])
608
609 {-
610   Declaring CCallable & CReturnable instances in a module different
611   from where the type was defined. Caused by importing data type
612   abstractly (either programmatically or by the renamer being over-eager
613   in its pruning.)
614 -}
615 invisibleDataConPrimCCallErr clas inst_ty
616   = hang (hsep [ptext SLIT("Constructors for"), quotes (ppr inst_ty),
617                 ptext SLIT("not visible when checking"),
618                 quotes (ppr clas), ptext SLIT("instance")])
619         4 (hsep [text "(Try either importing", ppr inst_ty, 
620                  text "non-abstractly or compile using -fno-prune-tydecls ..)"])
621
622 methodCtxt     = ptext SLIT("When checking the methods of an instance declaration")
623 superClassCtxt = ptext SLIT("When checking the superclasses of an instance declaration")
624 \end{code}