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